jquery与servlet交互的json问题

2019-03-25 13:43|来源: 网路

框架用烦了,目前只用servlet和jquery,servlet返回json数据,jquery在前面无刷新的解析,原来用struts2自带的jsonplugin,现在用google-gson包生成json字符串,但是为什么不行呢?
前台页面jquery请求后台servlet:
$(document).ready(function(){
$("#b_submit").click(function(){
$.ajax({
type:"POST",
url:"buttonSubmit",
data:{
id:1,
name:"zhang"
},
success:function(data){
alert(data.list);
},
dateType:"json"
})
});
})
后台servlet代码:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//response.setContentType("application/x-json");
response.setContentType("text/html;charset=utf-8"); 
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String id = request.getParameter("id");
System.out.println(name);
System.out.println(id);
List<TestBean> tbList = new ArrayList<TestBean>();
TestBean tb = new TestBean();
tb.setId(id);
tb.setName(name);
tbList.add(tb);
TestBean tb2 = new TestBean();
tb2.setId("2");
tb2.setName("gu");
tbList.add(tb2);
Gson gson = new Gson();
HashMap<String,List<TestBean>> map = new HashMap<String,List<TestBean>>();
map.put("list", tbList);
out.print(gson.toJson(map));
out.close();
}
但是为什么不行呢?有朋友说要换成response.setContentType("application/x-json");但是我也试了,也不行,页面用data.list时总是undefined,用data.length,它会按string的长度返回来,后来用JSON.parse来转换是可以的,但我觉得这样麻烦,如果能返回json数据,又何必再转换一下呢?效率就降低了,请大家帮助!
问题补充:
我返回来的是一个类似的json格式的字符串,但是我用js去判断的时候,会有问题:
例如:{"list":[{"id":1,"name":"gu"},{"id",2,"name":"zhang"}]}
我用data.list取不到值啊,这是为什么呢?以前集成struts2框架时都是可以的

相关问答

更多