1、通过requset读取ajax传参:
@RequestMapping("/addError")
@ResponseBody
public Boolean add(HttpServletRequest request, HttpServletResponse response) {
ErrorLog eLog = new ErrorLog();
eLog.setName(request.getParameter("name").toString());
eLog.setErrorXq(request.getParameter("errorXq").toString());
eLog.setCreatDate(new Date(System.currentTimeMillis()));
eLog.setBz(request.getParameter("bz").toString());
lErrorService.add(eLog);
return true;
}
$.ajax({
type:'post',
url:'http://localhost:8080/ssm/addError',
dataType:'json',
data:{name:'渣成沙',errorXq:'测试',bz:'yog'},
success:function (res) {
resule(res,'新增');
}
});
2、通过传实体类方式:
@RequestMapping("/updateErrorLog")
@ResponseBody
public Boolean update(HttpServletRequest request,HttpServletResponse
response,@RequestBody ErrorLog eLog) {
lErrorService.upErrorXq(eLog);
return true;
}
$.ajax({
contentType: "application/json; charset=utf-8",
type:'POST',
url:'http://localhost:8080/ssm/updateErrorLog',
data:JSON.stringify(data),
success:function (res) {
resule(res,'编辑');
}
});
第二种格式使用时遇到两个问题:
1、在ajax请求没有添加 contentType: "application/json; charset=utf-8"时会报 Failed to load resource: the server responded with a status of 415。
2、在ajax请求时没有将参数转成JSON,导致与后台实体不符,切记仔细添加JSON.stringify(data)。

本文详细介绍了如何使用Ajax与SpringMVC进行数据交互,包括通过request对象读取Ajax传参的方法,以及如何传递实体类。同时,文章还解决了在使用JSON数据格式时常见的415错误和数据类型不匹配问题。
2081

被折叠的 条评论
为什么被折叠?



