写在前面:
1、源代码来源于博客http://blog.sina.com.cn/u/2904067371 ,在此基础上对于前端代码稍作更改,把传过来的数据解析并传入表格
2、json解析,用eval()
3、写入表格 table.rows[i].cells[j].innerHTML
4、导入java中json应用的jar包(如果没有导入jar包或者包不全就不会有import net.sf.json.JSONArray;import net.sf.json.JSONObject;
JSONArray、JSONObject会报错。
)
5、测试字符串如下:{"person":[{"id":3,"name":"ss","pwd":"1234"},{"id":23,"name":"ws","pwd":"124"}]}
json jar包百度云:
http://pan.baidu.com/s/1i3GNJ9N
工程截图:
效果截图:
代码:
Person.java
package com.orilore.gb; public class Person {
public int getId() {
return id;
} public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
private int id;
private String name;
private String pwd; }
servlet json.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/xml;character=utf-8");
response.setHeader("Cache-Control", "no-cache");
try{
Person p =new Person();
p.setName("ss");
p.setId();
p.setPwd(""); Person p1 =new Person();
p1.setName("ws");
p1.setId();
p1.setPwd("");
List<Person> list =new ArrayList<Person>();
list.add(p);
list.add(p1);
try{ JSONArray json =JSONArray.fromObject(list);
JSONObject jb =new JSONObject();
jb.put("person", json);
response.getWriter().write(jb.toString());
}catch(IOException e){
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
} }
前端页面代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<input type="button" onclick="validate()" value="dsfdsafa" >
<div id="div"></div>
<table border="" style="width:300px;height:200px;" id="table">
<tr id="tr" border=""><td></td>
<td></td>
<td></td></tr> <tr border=""><td></td>
<td></td>
<td></td></tr></table>
<script type="text/javascript"> function validate(){
var div=document.getElementById("div");
var xmlhttp;
var table=document.getElementById('table'); if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState== && xmlhttp.status==){
var x=xmlhttp.responseText
div.innerHTML=x;
var sd=eval("(" + x + ")"); var arr=new Array();
var i=;
for(var a in sd.person){//获取有几个person
var count=;//计算person属性值的个数
i++;
for(var item in sd.person[a])
{ count++;
var p=sd.person[a][item];//得到属性值的内容
table.rows[i-].cells[count-].innerHTML=p;//把内容填向table表格
}
}
}
}
var url ="json";
xmlhttp.open("POST",url,true);
xmlhttp.send(); }
</script>
</body>
</html>