Sachin Divakar Sachin Divakar - 3 months ago 12
Ajax Question

Display Json using jquery ajax as response to post request to jsp page

Code to display json data



$(document).ready(function(){
$("button").click(function(){
$.ajax({
url:"jsonCreation.jsp",
type:'post',
dataType: 'json',
success: function(data) {

alert(eval("data = "+data.phone+";"));
$('#email').val(data.email);
}
});



});
});


Code to create json response



<%

try{


//connection statenebt
JSONArray respJson = new JSONArray();
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();




while (rs.next()) {

JSONObject obj = new JSONObject();
for (int i = 1; i < numColumns + 1; i++) {

String columnName = rsmd.getColumnName(i);
obj.put(columnName, rs.getString(columnName));

}
respJson.put(obj);


}


//respJson.toString();
out.println(respJson.toString());
System.out.println(respJson);

}
catch(Exception e)
{
System.out.println(e);
}

%>


Output



[{
"phone":"XXXX",
"fax":"XXX",
"website":"www.xxxx.xx",
"enterpriseName":"XXXXLIMITED",
"enterpriseId":"1001",
"factoryAddress":"",
"isActive":"1",
"category":"Financial Services",
"chairmanName": "XXXX",
"administrativeDept ":"Industries Department",
"incorporationDate":"XXXXX",
"email":"XXXX.com",
"incorporationAct":"Companies Act,1956",
"mdName":"XXXXX",
"officeAddress":"XXXXXX",
"activities":"XXXXX for industries XXXXXXXX"
}]


How to access from website



Previously i used this code

$.get("jsonCreation.jsp",function(data,status){

alert(data.phone);
alert(data.email);
});

>The output of alert was


undefined

Answer
var row= $('<tr> </tr>').appendTo('#tab');  

$.each(responseJson, function(key, value) {   
    //alert(value.enterpriseName);
    //alert(responseJson);

    console.log(responseJson[key].website);
        $('<td> </td>').text(responseJson[key].enterpriseName).appendTo(row);
        $('<td> </td>').text(value.phone).appendTo(row);
        $('<td> </td>').text(value.website).appendTo(row);
 }
Comments