This is the 23rd day of my participation in Gwen Challenge
Relearn JavaScript in a series of articles…
The problem
The front-end Ajax request sends an array, and the back-end interface receives a null.
Front-end Ajax requests:
Let data = {ids:[1,2,3,4]} Ajax ({type:"POST", url:"user/saveUser", dataType:"json", contentType:"application/json", data:data, success:function(data){ } });Copy the code
Back-end interface definition:
public
Copy the code
Ideally, the interface would receive successfully, but it doesn’t.
why
This is because ajax requests deeply serialize parameters by default, but the Servlet API cannot handle this, resulting in null received by the interface. After deep serialization, the interface parameters are: IDS []= 1&IDS []= 2&IDS []=3.
The solution
The solutions to this problem are as follows:
-
Shallow serialization (parameter serialization) is used in the traditional way by setting the Ajax request to: traditional:true, passing the data parameters as ids=1& IDS =2& IDS =3. Interface parameters can be obtained without modification.
-
Convert the array passed to a string, and transfer through a string. {ids: json.stringify ([1,2,3])}, the back-end interface needs to be adjusted accordingly.
Knowledge extension
JSON serialization
JSON serialization is the process of processing a JSON object into a JSON string to facilitate data transfer. This can be done via json.stringify () or the object custom toJSON() function.
- JSON. Stringify () function
Usage:
// object: the object to be serialized // replacer: This parameter is optional. If it is a function, every value to be serialized will be processed by this function during the serialization process. // If it is an array, it means that only the attributes in the array are involved in the serialization. // space: An optional argument that specifies a blank string to indent to beautify the output. The minimum value is 1 and the maximum value is 10. Json.stringify (object,replacer,space)Copy the code
Here’s an example:
var obj = { name:'zhangsan', age:12, hobits:['ball','games'] } // 1. Var replacer = function(key,value){if(typeof value==='string'){return value.toupperCase ()} return {name:'ZHANGSAN', age:12,hobits:['BALL','GAMES']} JSON. Stringify (object,replacer) // 2. Var replacer = ['name'] // output :" {"name":" Tom "}" json.stringify (object,replacer)Copy the code
Why are arrays also converted to uppercase letters?
JSON serialization, if the property is an object or array, continues until the property value is a primitive type, function, or Symbol type.
- Customize the toJSON() function
If the object being serialized has a toJSON() function, the toJSON() function overrides the default serialization behavior, and the serialized value becomes the return value of the toJSON() function. It provides more precise serialization control and can be interpreted as a complement to the Stringify function.
Var object = {name:' toJSON ', age:12, city:' Beijing ', toJSON:function(){// The arrow function cannot be used here because executing object.tojson () inherits the parent scope, Return {Name:this.name, Age:this.age}} JSON. Stringify ({Name: object},[' Name ']) // Output: "{" Name ":{}}"Copy the code
-
After the object. The toJSON () returns the {” Name “:” zhang “, “Age” : 12}, the serialization change {” Name “: {” Name” : “zhang”, “Age” : 12}}
-
The second parameter replacer is the array [“name”], which filters the name attribute, but the name attribute is an object, so the recursive serialization of the object’s attributes, where there is no name, is an empty object {}.
JSON deserialization
JSON antisequence is the process of converting a JSON string to a JSON object, either through the json.parse () function or through eval().
- JSON.parse()
The basic usage is as follows:
Reviver: An optional argument. If it is a function, it specifies how the original value is parsed before being returned. JSON.parse(text,reviver)Copy the code
Examples are as follows:
var text = "{"name":"zhangsan","age":12,"hobits":["ball","games"]}" JSON.parse(text,function(key,value){ If (key==='name'){return value+' student '} return value}) {name:' student ', age:12, hobits:['ball','games']}Copy the code
- The eval () function
The eval() function evaluates a JavaScript string and executes it as a script.
Var text = '{" name ":" zhangsan ", "age" : 12, "hobits" : [" ball ", "games"]}' var object = eval (" (" + text + ") ") / / output: { name:'zhangsan', age:12, hobits:['ball','games'] }Copy the code
conclusion
So far we’ve looked at serialization and deserialization.