Jquery发送ajax请求以及datatype参数为text/JSON方式

Jquery发送ajax请求以及datatype参数为text/JSON方式
1、方式一:datatype:'text'
2、方式二:datatype:'JSON'
3、使用gson-1.5.jar包和json-2.2.jar包处理JSON代码
(注:
使用json-2.2.jar包时,传给前端的结果,获取时不是json对象,需要var json = eval_r("("+data+")");转义一下。
而使用gson-1.5.jar包时,传给前端的结果就是json对象。无需进行转义。
 
1、方式一:datatype:'text'
 
1.1 页面端的ajax请求:
$.ajax({
type: "POST",
url: "<%=basePath%>getAllUser.action?randomNum="+new Date().getTime(),
data : {},
datatype : 'text',
cache: false,
async: false,
success:function(data) {
strHtml = data的处理结果; //对data数据进行处理,拼接成html代码块
$("#userList").html(strHtml); //也可以使用:$("#userList").append(strHtml);
}
},
error:function(){
alert("获取用户信息失败,请联系管理员!");
}
});//end ajax 

1.2 后台java代码处理:

public String getAllUser(){
response.setContentType("text;charset=UTF-8");// 设置返回的文档类型
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter out = null;
String text = "";
try {
out = response.getWriter();
} catch (Exception e) {
text = "false";
logger.error(e.getMessage());
}
//TODO 获取所有用户信息,遍历
//text = "userId1,userId2,userId3";
out.print(text);
out.flush();
out.close();
return null;
}
 

2、方式二:datatype:'JSON'

 
2.1 页面端的ajax请求:
$.ajax({
type: "POST",
url: "<%=basePath%>getAllUser.action",
datatype : 'JSON',
cache:false,
success : function(data) {
$.each(data,function(entryIndex,entry){
var userId=entry.id;
var userName=entry.userName;
......
// TODO strHtml = 构造显示的html代码块;
 
// 以追加方式进行填充内容
$("#userList").append(strHtml);
 
});//end each
}// end success
});//end ajax
 

2.2 后台java代码处理:

public String getAllUser() throws Exception {
try {
response = ServletActionContext.getResponse();
response.setContentType("application/json");
response.setCharacterEncoding("gbk");
 
List<User> userList = new ArrayList<User>();
for (int i = 0; i < size; i++) {
User user = new User();
user.setUserId(i);
user.setUserName("kobicc" + i);
......
//这个逻辑需要从数据库中获取结果即可。
 
userList.add(user);
}
 
//com.google.gson.Gson  gson-1.5.jar包中的类文件
Gson gson = new Gson();
 
String jsonString = gson.toJson(userList);
 
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
out.close();
return null;
} catch (Exception e) {
throw new RuntimeException("获取用户信息失败!");
}
}

3、使用gson-1.5.jar包和json-2.2.jar包处理JSON代码

 
3.1 使用gson-1.5.jar包处理JSON代码
——参考《2、方式二:datatype:'JSON'》的处理方式
 
3.2 使用json-2.2.jar包处理JSON代码
3.2.1 页面端的ajax请求:
$.ajax({
type: "POST",
url: "<%=basePath%>getAllUser.action",
datatype : 'JSON',
cache:false,
success : function(data) {
//!!!重要,需要使用一下这个将data变为JSON对象
var json = eval_r("("+data+")");
 
//alert(json.nUserListCount);
 
//TODO 进行后续逻辑操作
 
}// end success
});//end ajax
 

3.2.2 后台java代码处理:

public void getAllUser() throws Exception {
try {
response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
 
//net.sf.json.JSONArray json-2.2.jar包中的类文件
 
JSONArray objs = new JSONArray();
JSONObject json = new JSONObject();
JSONObject returnJSON = new JSONObject();
List<User> userList = userService.getAllUser();
int nUserListCount = 0;
nUserListCount = userList.size();
 
for (User user : userList) {
json.element("userNo", user.getUserNo());
json.element("userName", user.getUserName());
......
objs.add(json);
}
returnJSON.put("userList", objs);
returnJSON.put("nUserListCount", nUserListCount);
 
response.getWriter().write(returnJSON.toString());
} catch (Exception e) {
logger.error("获取用户信息失败!", e);
throw new RuntimeException("获取用户信息失败!");
}
}
原文地址:https://www.cnblogs.com/zhujiabin/p/5090385.html