-1

I want to display data from servlet which returns json. No errors on the console and also I don't have the result.

file.js:

$("#json_disp").click(function(){
$.ajax({
url : 'Servlet',
dataType: 'json',
success : function(json) {
$("#res").html(json.user);
}
});

file.html:

<body>
    <input type="button" value="display" id="json_disp">
    <div id="res"></div>
</body>

Servlet.java

JSONObject json = new JSONObject();
User u = new User();
u.setId(1);
u.setName("Jhon");
json.put("user", u);
out.println(json);
out.flush(); 
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
mak_doni
  • 565
  • 1
  • 10
  • 29

1 Answers1

0

try this:

     User u = new User();  
     u.setId(1);  
     u.setName("Jhon");  

    JSONObject obj=new JSONObject();
    obj.put("u_id",user.getId());
    obj.put("u_name",user.getName());
    out.println(json);
    out.flush(); 

and change the display names accordingly in the jquery snippet.

GionJh
  • 2,742
  • 2
  • 29
  • 68
  • you are welcome, your understanding of the JSONObject class needs to be improved :) – GionJh Mar 26 '15 at 18:34
  • thanks GionJh, i want to display the information of 2 users, u.setId(1); u.setName("Jhon"); u.setId(2); u.setName("Mike") . i tried to do this attempt : JSONArray list = new JSONArray(); User u = new User(); u.setId(1); u.setName("Jhon"); u.setId(2); u.setName("Mike"); list.add(u.getId()); list.add(u.getName()); out.print(list); out.flush(); but just the information of one user is displayed – mak_doni Mar 27 '15 at 11:16
  • this could help: http://stackoverflow.com/questions/18983185/how-to-create-correct-jsonarray-in-java-using-jsonobject – GionJh Mar 27 '15 at 11:43
  • i tried this attempt :JSONObject jo = new JSONObject(); jo.put("firstName", "John"); jo.put("lastName", "Doe"); JSONArray ja = new JSONArray(); ja.add(jo); JSONObject mainObj = new JSONObject(); mainObj.put("employees", ja); out.println(mainObj); and in the js file i wrote $("#res").html(json.mainObj); but i don't have any result – mak_doni Mar 27 '15 at 13:42