public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
response.setContentType("text/html;charset=utf-8");
JSONObject json = null;
PrintWriter out = response.getWriter();
System.out.println("load in ....");
// 初始化数据
class Cat{
Cat (String name,int height ) {
this.height = height;
this.name = name;
}
int height;
String name;
}
ArrayList<Cat> list = new ArrayList<Cat>();
list.add(new Cat("Tom",20));
list.add(new Cat("Abby",30));
list.add(new Cat("Kitty",10));
list.add(new Cat("Julie",40));
// 定义返回值的容器
StringBuffer buffer = new StringBuffer();
// 当json返回 对象时,外面必须加一对小括号
buffer.append("({");
for(int i = 0; i < list.size(); i++){
Map map = new HashedMap();
map.put("name",list.get(i).name);
map.put("height",list.get(i).height);
json = JSONObject.fromObject(map);
buffer.append(i);
buffer.append(":");
buffer.append(json.toString());
if(i != list.size()-1) {
buffer.append(",");
}
}
buffer.append("})");
out.print(buffer);
out.flush();
out.close();
}
js脚本
$(function() {
$("#verify").click(function(){
var userName = $("#userName").val();
$.ajax({
type: "post",url: "servlet/ResultJSON",async: true,data : "name=" + userName,dataType: "Text",success: function(data){
alert(data);
var objs = eval(data);
try{
for (var i = 0; i < 10; i++) {
var o = objs[i];
$("#result").append(o.name + "---" + o.height + "<br />");}
}catch(e){
alert("数据往下没有了");
}
}
});
});
});