特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處:
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 }