1.post请求方式一,指定contentType
contentType为application/json时,data的类型要转换成json字符串的形式
$.ajax({
type : "POST",
url : "/mailbox/sendMail/resend",
dataType : "json",
data : JSON.stringify(ids),
contentType:"application/json;charset=utf-8",
success : function(d) {
alert("成功");
}
});
后台接收:要使用@RequestBody注解接收前端传递的参数
@RequestMapping(value = "/resend", produces = "application/json;charset=utf-8")
public @ResponseBody String resend(@RequestBody List<Long> ids) {
return "success";
}
再如前端请求
$.ajax({
type : "post",
url : "/intelligentAllocate/createAllocateDemand",
data : JSON.stringify(obj),
contentType:'application/json;charset=utf-8',
dataType : "json",
success : function(data) {
}
});
后台接收
@RequestMapping(value = "/createAllocateDemand", produces = "application/json;charset=utf-8")
public @ResponseBody String createAllocateDemand(@RequestBody AllocateDemandPoJo demandPoJo) {
Result result = this.getResult();
try{
try {
User user = this.getLoginUser();
demandPoJo.setCode(orderNumberService.nextOrderCode(OrderType.DB.name(), user));
demandPoJo.setType("SALE");
long num = allocateDemandService.add(demandPoJo, user);
if(num>0){//添加成功
result.setCode(ResultStatus.SUCCESS);
}else{//添加失败
result.setCode(ResultStatus.FALSE);
}
} catch (Exception e) {
e.printStackTrace();
result.setCode(ResultStatus.ERROR);
}
} catch (ServiceException e) {
e.printStackTrace();
result.setCode(ResultStatus.FALSE);
result.addMsg(e.getMsg());
} catch(Exception e){
e.printStackTrace();
}
return this.getI18nResult(result);
}
2.post请求方式二:$.post() 方法使用 HTTP POST 请求从服务器加载数据。
请求的参数是json对象类型
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
$.post(
"/amazonReport/reportSearch/1/50",
{ name: "John", time: "2pm" },
function(data) {
console,log(data);
});
后台接收
@RequestMapping(value = "/reportSearch/{pageNum}/{pageSize}", produces = "application/json;charset=utf-8")
public ModelAndView reportSearch(AmazonReportRequestInfo amazonReportRequestInfo, HttpServletRequest request, HttpSession session,
Boolean defaultSearch) {
return null;
}
3.如果前端使用 $.post()方式提交请求 ,data所传数据类型为json字符串,后端使用@RequestBody接收请求参数时会报错
Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)
使用post方式提交请求 使用方式1 或者方式2 ,混合使用会导致3这种报错