使用 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;
}
此时问题解决。