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("獲取用戶信息失敗!");
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM