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 }