简介:
JSONObject就是常说的json,其格式为{“key1”:value1,”key2”,value2….};key 必须是字符串,因为ajax请求不刷新页面,但配合js可以实现局部刷新,因此json常常被用作异步请求的返回对象使用,通过response.getWriter()获取PriteWriter pw,然后pw.print(json).
如果没有设置response.setContentType(“application/json;charset=utf-8”);则需要自己在js中进行解析。
举例:
response.setContentType("application/json; charset=utf-8");
PrintWriter pw = response.getWriter();
Student s = new Student(“邓江山”,12);//反正就是构造一个对象,有没有数据无所谓
JSONObjet json = JSONObjet .from(s);//将s转化成json对象。
pw.print(json);
pw.flush();
pw.close();
这个json对象就传到你发送请求的那个jsp上面,而 $.post(url,data.function(data){}) 这里的data就是后台返回的值,也就是这里的json只需要 var json=data;就获取到了,再取得原来Student的属性var name=json.name(student的name属性)
创建JSONObject对象
private static JSONObject createJSONObject(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","huangwuyi");
jsonObject.put("sex", "男");
jsonObject.put("QQ", "999999999");
jsonObject.put("Min.score", new Integer(99));
jsonObject.put("nickname", "梦中心境");
return jsonObject;
}
比较request.setAttribute(“key”,value);这个必须配合forward来转发跳转到需要这个value的jsp页面,页面进行刷新