使用 Ajax 向後臺傳值時,後臺能接受到請求,處理後返回到 Ajax 中判斷結果時錯誤,此時在瀏覽器控臺輸出結果爲一個頁面。
前臺的 Ajax 部分代碼如下:
//ajax
$(function () {
$.ajax({
headers: {
Accept: "application/json; charset=utf-8"
},
type: "post",
async: true,
url: "/modifyImage",
timeout: "3000",
data: {
"imgModInfo": JSON.stringify(imgModInfo)
},
dataType: "json",
success: function (data) {
if (data.result === "success"){
alert("修改成功!");
location.reload();//刷新
}else {
console.log(data);
alert("修改失敗!");
}
},
error: function (e) {
console.log(e);
}
});
});
請求後臺代碼中,之前採用的是 modelAndView 方式傳值,如下:
@RequestMapping(value = "/modifyImage")
@ResponseBody
public ModelAndView modify(HttpServletRequest request, Model model) throws Exception{
String imgModInfo = request.getParameter("imgModInfo");
ModelAndView modelAndView = new ModelAndView();
try{
int modCounts = imageService.updateImage(imgModInfo);
// 修改失敗
if (modCounts <= 0){
logger.error(String.format("服務器修改 images 失敗!images: %s", imgModInfo));
modelAndView.addObject("modResult","failure");
modelAndView.setViewName("images.html");
return modelAndView;
}else {
logger.info(String.format("服務器修改 images 個數:%s", modCounts));
}
}catch (Exception e){
e.printStackTrace();
request.setAttribute("modResult", "failure");
}
modelAndView.addObject("modResult","success");
modelAndView.setViewName("images.html");
return modelAndView;
}
採用這種方式返回,在 Ajax 中接受到的返回爲一個頁面,控臺輸出如下:
status:200 說明請求成功,readyState 爲4,說明 Ajax 訪問正常,但是問題出在哪呢?主要就在後臺 controller 的返回值上。
當返回的是字符串或者 modelAndView 對象時,前臺 Ajax 接受到的數據不是標準的 Json 格式的字符串或對象,無法解析爲 json 格式的數據,故報錯進入到 Ajax 中的 error 部分。
修改後的 controller 方法即改變返回值類型即可,如返回 map 類型。
@RequestMapping(value = "/modifyImage", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> modify(HttpServletRequest request) throws Exception{
String imgModInfo = request.getParameter("imgModInfo");
Map<String, Object> map = new HashMap<>();
try{
int modCounts = imageService.updateImage(imgModInfo);
// 修改失敗
if (modCounts <= 0){
logger.error(String.format("服務器修改 images 失敗!images: %s", imgModInfo));
map.put("result", "failure");
return map;
}else {
logger.info(String.format("服務器修改 images 個數:%s", modCounts));
}
}catch (Exception e){
e.printStackTrace();
request.setAttribute("result", "failure");
}
map.put("result", "success");
return map;
}
此時問題解決。