ajax获取显示list数据

1、servlet中处理

//转回为可以用eval方法运行的字符串格式
String html = "[";
for(int i = 0;i0)
		html += ",";
	html += "{id:'"+list.get(i).getId()
			+"',name:'"+list.get(i).getName()
			+"',author:'"+list.get(i).getAuthor()
			+"',price:'"+list.get(i).getPrice()+"'}";
}
html += "]";
resp.getWriter().write(html);

2、JavaScript中处理:

eval()方法中的字符串加对括号,以免出错


3、用gson插件

A)导入gson.jar

B)JavaScript中$.post(“glist”,fuciont(date)(),’json’)

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//处理乱码
	resp.setCharacterEncoding("utf-8");
				
	//假装从数据库获得数据
	List list = new ArrayList();
	list.add(new Book(1,"java","sun",12.1));
	list.add(new Book(2,"java编译原理","sun",13.2));
	list.add(new Book(3,"易语言","不知道",14.2));
		
	Gson gson = new Gson();
	resp.getWriter().print(gson.toJson(list));
}

 

你可能感兴趣的:(#,初学servlet,jsp)