JQuery use JSON to read JavaBean List

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Read JavaBean
1, A JavaBean
Java code:
response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  StuBean stu = new StuBean();
  stu.setId("s001");
  stu.setName("Jahson");
  stu.setPassword("123456");
  JSONObject jsonObject = JSONObject.fromObject(stu); 
out.println(jsonObject.toString());//Put a JSON into the page
  System.out.println(jsonObject);
  out.flush();
  out.close();
JQuery code:
$.getJSON("servlet/MoreJson",function(data){
     var str=status+"<br>";
     str+="<table border=\"1\">";    
     str+="<tr>";
     str+="<td>"+data.id+"</td>";
     str+="<td>"+data.name+"</td>";
     str+="<td>"+data.password+"</td>";
     str+="</tr>";
     str+="</table>";
     $("#res").append(str);
    });
2, Multiple JavaBean
Java code:
response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  StuBean stu = new StuBean();
  stu.setId("s001");
  stu.setName("Jahson");
  stu.setPassword("123456");
  StuBean stu2 = new StuBean();
  stu2.setId("s002");
  stu2.setName("Jack");
  stu2.setPassword("654321");
  List list = new ArrayList();
  list.add(stu);
  list.add(stu2);
  JSONArray jsonArray = JSONArray.fromObject(list); 
  out.println(jsonArray.toString());
  System.out.println(jsonArray);
  out.flush();
  out.close();
JQuery code:
$.post("servlet/MoreJson",{parma:v},function(data,status){
     var str="<table border=\"1\">";
     $.each(data,function(index,content){
      str+="<tr>";
      str+="<td>"+content.id+"</td>";
      str+="<td>"+content.name+"</td>";
      str+="<td>"+content.password+"</td>";
      str+="</tr>";
     });
     str+="</table>";
     $("#res").append(str);
    },"json");
Read List
Java code:
response.setContentType("text/html");
  PrintWriter out = response.getWriter(); 
  List<String> list = new ArrayList<String>();
list.add("Chengdu");
list.add("Mianyang");
list.add("Xichang");
  list.add("aaa");
//If it is List, it must use JSONArray instend
  JSONArray jsonArray = JSONArray.fromObject(list);
  out.println(jsonArray.toString());
  out.flush();
  out.close();
JQuery code:
$.post("servlet/MoreJson",{parma:v},function(data,status){
     var str="<table border=\"1\">";
     $.each(data,function(index,content){
      str+="<tr>";
      str+="<td>"+content+"</td>";
      str+="</tr>";
     });
     str+="</table>";
     $("#res").append(str);
    },"json");
Conclusion: List through each traversal data information; the individual object directly call, multiple objects in the LIst through the each traversal
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Chris at December 16, 2013 - 4:40 PM