I. Passing a JSON single value or object
1. Front End
1 vardata = {' id ': ID, ' name ': name};2 $.ajax ({3Type: "POST", 4URL: "User/saveuser", 5DataType: "JSON", 6 //contentType: "Application/json",//Cannot add this header7Data:data,//there is no json.stringify to send the requested data in: Form data8Successfunction(data) {9 Ten } One});
2. Back end
//viewed as a single value@RequestMapping (value = "Save", method ={Requestmethod.post}}) @ResponseBody Public voidSave (@RequestParamintId,string name) {//here the field to be consistent with the front end, @RequsetParam can not add, the default is to call it }//seen as an object@RequestMapping (value = "Save", method ={Requestmethod.post}}) @ResponseBody Public voidSave (user user) {//front-end fields are consistent with object properties//automatic conversion to object change}
Two. The JSON object is converted into a string and then passed the value
1.1. Front-end
$.ajax ({ type:"POST", URL:"User/saveuser", DataType:"JSON", ContentType://need to add this header // Send the requested data at Request payload success: function (data) { }
1.2, back-end
// As object @RequestMapping (value = "Save", method = {requestmethod.post}}) @ResponseBody publicvoid//need to add requestbody annotation // Auto Convert to object }
Three. After the object is json.stringify, it is passed in the first way and can be implemented in object {' UserList ': Users, ' Key1 ': value1}
1. Front Desk
var user = {' id ': ID, ' name ': name}; var jsonstrgoods = json.stringify ({' gid ': GID,...}); $.ajax ({ type:"POST", URL:"User/saveuser", DataType:"JSON", // contentType: "Application/json",//Do not add this header // send the requested data at Request payload Success:function(data) { }
2. Backstage
//viewed as a single value@RequestMapping (value = "Save", method ={Requestmethod.post}}) @ResponseBody Public voidSave (@RequestParam String user,string goods) {//here the field to be consistent with the front end, @RequsetParam can not add, the default is to call itUser u= json.parseobject (user, user.class);//Alibaba.fastjson Convert to Object }//seen as an object@RequestMapping (value = "Save", method ={Requestmethod.post}}) @ResponseBody Public voidSave (Userandgoods ug) {//never tried, guess so, front-end fields are consistent with object properties//automatic conversion to object change}
Summary: 1. If you use Json.stringify () to convert an object to a string, you need to specify ContentType as Application/jsonin the AJAX request, and the background needs to be added @ Requestbody annotations;
2. If the direct JSON object is the opposite of the above, you cannot specify ContentType as Application/json, whose default type is application/x-www-form-urlencoded
Springmvc several ways to send AJAX requests to the front end