一. 問題描述
前端發送ajax請求給后端, 后端收到, 正常返回String
, 但前端ajax的回調方法success
沒有響應
前端代碼
function sendMsg(msg, uname) {
$.ajax({
url: "/chat",
type: "post",
data:'message='+msg+'&username='+uname,
dataType: "json",
success: function (data) {
console.log("receive data : " + data);
}
});
}
后端代碼
@RequestMapping("/chat")
@ResponseBody
public ServerResponse chat(String message, String username) {
System.out.println("------------ chat message is : " + message + " chat user is : " + username + " ------------------");
return "success";
}
二. 原因
后台返回的json
數據是一個純String
類型的對象時,前端dataType
屬性設置為json
后,會認為這個由String
對象轉換的json
數據格式不是標准的json
格式, 固前端認為出錯了, 不進回調方法: success
三. 解決, 有兩種方法
1. 改前端代碼, 后端不變: 前端ajax請求中的dataType
屬性設置為text
即可
function sendMsg(msg, uname) {
$.ajax({
url: "/chat",
type: "post",
data:'message='+msg+'&username='+uname,
dataType: "text",
success: function (data) {
console.log("receive data : " + data);
}
});
}
2. 改后端代碼, 前端不變: 后端封裝為一個json
的字符串即可
@RequestMapping("/chat")
@ResponseBody
public ServerResponse chat(String message, String username) {
System.out.println("------------ chat message is : " + message + " chat user is : " + username + " ------------------");
return "{\"result\":\"success\"}";
}