Question

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
Was it helpful?

Solution 3

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);
 }

OTHER TIPS

Use data[0] instead of data , since you are using array of object

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

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

You have an ARRAY of objects, so reference the index:

data[0].website;

You can also loop if you have an array of more than 1 object:

for (var i = 0; i < data.length; i++) {
    console.log(data[i].website);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top