This time I will show you how to deal with errors when Ajax transmits json format data to the background. What are the things to note when handling errors when Ajax transmits json format data to the background? The following is a practical case. Get up and take a look.
Problem description: Ajax transmits json format data to the background and reports a 415 error, as shown in the figure below
Page code
function saveUser(){ var uuId = document.getElementById("uuid").value; var idCard = document.getElementById("idCard").value; alert(uuId+idCard); // var result = new Object(); // result.uuId = uuId; // result.idCard = idCard; // var saveData = JSON.stringify(result); // alert(saveData); $.ajax({ url : "xdds/saveUser.do?random=" + Math.random(), type : "post", data : {"uuid" : uuId,"idCard" : idCard}, // data:saveData, dataType : 'json', // contentType : "application/json", success:function(data){ } }); }
Background code
@RequestMapping(value = "/saveUser.do", method = { RequestMethod.POST }) @ResponseBody public Map<String, Object> saveUser (@RequestBody MapUser user){ Map<String, Object> map = new HashMap<String, Object>(); System.out.println(user.getUuid()+user.getIdCard()); map.put("result", "fda"); return map ; }
Error analysis: 415 (unsupported media type) The requested format is not supported by the requested page
Correct json format {key:value, key:value} Both key and value should have double quotes. The data value in the front-end code data above does not have double quotes, so an error is reported (because it is no problem to write the project in this way)
So the preliminary analysis may be a problem with the framework. Some frameworks can
data : {"uuid" : uuId,"idCard" : idCard} is encapsulated into the correct json format.
The specific reason is not yet known. The blogger is also a novice. I will share it when the blogger figures it out.
Solution: Open the code commented at the front deskvar saveData = JSON.stringify(result)<br>这个函数可以转化成真确的json格式。<br><br>ps:小白一个,有不对的地方请大神指正;有大神知道具
Recommended reading:
How to process the json data uploaded by ajax background successajax gets the return parameters of the page and gives Control assignmentThe above is the detailed content of How to deal with errors when Ajax transmits json format data to the background. For more information, please follow other related articles on the PHP Chinese website!