When using Ajax for requests and passing parameters, it is occasionally necessary to use an array as a pass-through parameter, which is a matter of using @requestbody to solve this problem
Processing on the page side:
(1) Use Json.stringify (arr) to convert a JSON object array into a JSON object string
(2) Set "ContentType" in Ajax parameters: "Application/json"
$(function(){ $("#exe"). On ("click",function(){ vararr =NewArray (); Arr.push ({"Name": "LCS", "age": 18}); Arr.push ({"Name": "yds", "age": 19}); Arr.push ({"Name": "Hrl", "Age": 20}); Arr.push ({"Name": "Lyf", "Age": 21}); varArrs =json.stringify (arr); $.ajax ({"url": "Ajax_array.do", ' type ': ' Post ', "Data": Arrs,"ContentType": "Application/json", "DataType": "JSON", "Success":function(Result) {alert ("The request was successful! "); }, "Error":function() {alert ("The request failed!" "); } }); }); });
In the back-end processing:
(1) using Requestbody to receive JSON object strings, JSON object strings (JSON object strings for arrays) converted from JSON object array into json.stringify (arr) persons
(2) Importing Json-lib, using its Jsonarray and Jsonobject methods to parse the data in the JSON object string
(3) Jsonarray.fromobject (persons) is the conversion of a JSON object string into a JSON object.
@ResponseBody @RequestMapping ("/ajax_array.do") //@RequestBody JSON string parameters to receive AJAX requests PublicString getpersons (@RequestBody person[] persons) {//Convert persons JSON string to JSON object//Jsonarray object, sort of like a list objectJsonarray Arrs =jsonarray.fromobject (persons); List<Person> personlist =NewArraylist<person>(); //Traverse Jsonarray for(inti=0; I<arrs.size (); i++) { person person=NewPerson (); //Getjsonobject (i) is a JSON objectString name = Arrs.getjsonobject (i). getString ("name"); intAge = Arrs.getjsonobject (i). GetInt ("Age"); Person.setname (name); Person.setage (age); Personlist.add (person); } System.out.println (Personlist); return"Success"; }
@RequestBody JSON string to receive Ajax