1.jquery1.3
2.json-lib.2.2.3 需要以下第三方jar包(http://json-lib.sourceforge.net/)
jakarta commons-lang 2.4
jakarta commons-beanutils 1.7.0
jakarta commons-collections 3.2
jakarta commons-logging 1.1.1
ezmorph 1.0.6
3.sevlet代码:
TestBean tb=new TestBean();
tb.setAddr("杭州西湖");
tb.setName("wangdong");
tb.setAge("27");
TestBean tb2=new TestBean();
tb2.setAddr("江西云中");
tb2.setName("xiaoqiang");
tb2.setAge("29");
List list=new ArrayList();
list.add(tb);
list.add(tb2);
JSONArray js = new JSONArray();
JSONArray jr=js.fromObject(list);
tb.setAddr("杭州西湖");
tb.setName("wangdong");
tb.setAge("27");
TestBean tb2=new TestBean();
tb2.setAddr("江西云中");
tb2.setName("xiaoqiang");
tb2.setAge("29");
List list=new ArrayList();
list.add(tb);
list.add(tb2);
JSONArray js = new JSONArray();
JSONArray jr=js.fromObject(list);
PrintWriter out = response.getWriter();
out.print(jr);
out.flush();
out.close();
out.flush();
out.close();
4.避免中文乱码,ajax只识别UTF-8编码
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/json;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
5.jsp代码
function test(){
$.getJSON(
"/servlet/TestJson",
function(data){
//alert(data.length);
//alert(data[0].name+""+data[0].addr);
$('#users tbody').empty();
for(var i=0;i<data.length;i++){
$('#users tbody').append('<tr>' +
'<td>' + data[i].name + '</td>' +
'<td>' + data[i].age + '</td>' +
'<td>' + data[i].addr + '</td>' +
'</tr>');
}
/*$.each(data.items, function(i,item){
alert(i);
$('#users tbody').append('<tr>' +
'<td>' + item.name + '</td>' +
'<td>' + item.age + '</td>' +
'<td>' + item.addr + '</td>' +
'</tr>');
});*/
}
);
}
$.getJSON(
"/servlet/TestJson",
function(data){
//alert(data.length);
//alert(data[0].name+""+data[0].addr);
$('#users tbody').empty();
for(var i=0;i<data.length;i++){
$('#users tbody').append('<tr>' +
'<td>' + data[i].name + '</td>' +
'<td>' + data[i].age + '</td>' +
'<td>' + data[i].addr + '</td>' +
'</tr>');
}
/*$.each(data.items, function(i,item){
alert(i);
$('#users tbody').append('<tr>' +
'<td>' + item.name + '</td>' +
'<td>' + item.age + '</td>' +
'<td>' + item.addr + '</td>' +
'</tr>');
});*/
}
);
}