1.jquery中調用ajax方法
$.ajax({
async:true,
type:"post",
url:"xxxServlet",
data:{"account":"jack","pwd":"123"},
success:function(data){
//dowork
},
//error:function(){alert("error!");},
dataType:"json"
});
注:指定dataType爲json時,不要用var obj = eval("("+data+")");去再次解析,會報錯
2.json格式
1.json對象
{key:value,key:value}
{"name":"jack","sex":"男","age":"25"}
2.json數組或集合格式
[{key:value,key:value},{key:value,key:value}]
[{"name":"jack","sex":"男","age":"25"}, {"name":"tom","sex":"男","age":"26"}]
3.json對象,數組嵌套
{
"param":[{key:value,key:value},{key:value,key:value}]
}
{
"param1":[{key:value,key:value},{key:value,key:value}],
"param2":[{key:value,key:value},{key:value,key:value}],
"param3":[{key:value,key:value},{key:value,key:value}]
}
{
"param1":"value1",
"param2":{},
"param3":[{key:value,key:value},{key:value,key:value}]
}
3.谷歌的gson包
Gson gson = new Gson();
String json = gson.toJson(car);
resp.getWriter().write(json);
4.阿里的fastjson包
JSON-jsonString(toJOSNString)
JSONObject-map集合(put)
JSONArray-list集合(add)
4.1.響應jsonString
String jsonString = JSON.toJSONString(car);
resp.getWriter().write(jsonString);
4.2.響應json對象
JSONObject data=JSONObject.parseObject(JSON.toJSONString(car));
resp.getWriter().print(data);
4.3.JSONObject對象
JSONObject jo = new JSONObject();
jo.put("message", "用戶名可註冊!");
resp.getWriter().print(jo);
4.4.JSONArray數組
JSONObject jo1 = new JSONObject();
JSONObject jo2 = new JSONObject();
JSONArray ja = new JSONArray();
ja.add(jo1);
ja.add(jo2);
resp.getWriter().println(ja);