1.如果是普通的json字符串,使用如下:
服务端:(只要ajax的格式正确,那么在servlet中使用out对象的write()方法输出,那么在ajax的success的回调方法中的data参数就是out对象的writer方法中输出的值)
JSONObject jsonArray = new JSONObject();
jsonArray.put(“wuyonghu”, “吴永胡”);
response.setContentType(“application/json; charset=UTF-8”);
// 已经将数据封装为一个JsonObject
PrintWriter out = response.getWriter();
// 将json对象转换为字符串传递到Jsp界面上去
out.write(jsonArray.toString());
out.flush();
前端:
$.ajax({
type : “POST”,
url : “http://localhost:8080/kkPlayer/GetCategoriesServlet“,
dataType : “json”,//此处要设置成jason
success : function(data) {
alert(data.wuyonghu); //输出结果为”吴永胡”
},
error : function() {
alert(“出现了错误”);
}
});
2.如果是JsonArray格式,解析如下:
服务端:
ArrayList<Kk_songcate> getsongCates = service.getsongCates();
// 得到了数据,现在将该数据封装为json
JSONArray jsonArray = new JSONArray();
JSONObject categoryesJsonObject = new JSONObject();
for (int i = 0; i < getsongCates.size(); i++) {
categoryesJsonObject.put("name", getsongCates.get(i)
.getCateName());
jsonArray.add(categoryesJsonObject);
}
// JSONObject jsonArray = new JSONObject();
// jsonArray.put("wuyonghu", "吴永胡");
response.setContentType("application/json; charset=UTF-8");
// 已经将数据封装为一个JsonObject
PrintWriter out = response.getWriter();
// 将json对象转换为字符串传递到Jsp界面上去
out.write(jsonArray.toString());
out.flush();
前端:
$.ajax({
type : “POST”,
url : “http://localhost:8080/kkPlayer/GetCategoriesServlet“,
dataType : “json”,//此处要设置成jason
success : function(data) {
alert(data[0].name);
/* $.each(data, function(key, value) {
alert(value.name);
}); */
},
error : function() {
alert(“出现了错误”);
}
});