Ajax传递复杂对象报415

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、问题描述

使用ajax进行post请求,参数为复杂对象,对象属性有数组,数组元素为对象。这种情况会报415错误。

ajax片段代码

 1 function test(){
 2     var url = "/api/demoController/add";
 3     var params = {
 4         "faceInfoList": [{
 5             "faceId": "1",
 6             "faceName": "leftFace"
 7         }, {
 8             "faceId": "2",
 9             "faceName": "rightFace"
10         }],
11         "personId": "123"
12     }
13     $.ajax({
14         url:"/api/demoController/add",
15         data:params,
16         type:"post",
17         dataType:"json",
18         async:true,
19         success:function(res){
20             if(res.success || res.code == 200){
21                 console.log(res);
22             }else{
23                 console.log(res);
24             }
25         },
26         error:function(res){
27             console.log(res);
28         },
29     });
30 }

2、解决方案

增加一行参数:contentType: "application/json;charset=UTF-8",

改了之后会报400,查了之后还需要增加参数。

ajax参数改为:data:JSON.stringify(params)

修改后完整的代码为:

 1 function test(){
 2     var url = "/api/demoController/add";
 3     var params = {
 4         "faceInfoList": [{
 5             "faceId": "1",
 6             "faceName": "leftFace"
 7         }, {
 8             "faceId": "2",
 9             "faceName": "rightFace"
10         }],
11         "personId": "123"
12     }
13     $.ajax({
14         url:"/api/demoController/add",
15         data:JSON.stringify(params),
16         type:"post",
17         dataType:"json",
18         contentType: "application/json;charset=UTF-8",
19         async:true,
20         success:function(res){
21             if(res.success || res.code == 200){
22                 console.log(res);
23             }else{
24                 console.log(res);
25             }
26         },
27         error:function(res){
28             console.log(res);
29         },
30     });
31 }

Java后台代码为:

1 @RequestMapping(value = "/add", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE)
2 @ResponseBody
3 public String add(@RequestBody InfoReq vo) throws IOException {
4     System.out.println(vo.toString());
5     return "Success";
6 }

3、参考网站

https://www.cnblogs.com/goblinn/p/9352267.html

posted @ 2019-11-19 19:47  mao2080  阅读(820)  评论(1编辑  收藏  举报