When jquery's Ajax method is called, jquery will serialize the parameter data based on the post or get protocol;
If the submitted data uses complex JSON data, for example:
{Userid: 32323, Username: {firstname: "Li", lastname: ""}}
The server cannot normally receive complete parameters because jquery serializes data and uses key-value pairs to assemble them;
Parameters are assembled into userid = 32323 & username = object; the object pointed to by username is serialized into a string "object"
How can I submit a complex object to the background action parameter?
First, solve jquery's problem of parameter serialization: CopyCode The Code is as follows:/* serialize an object to a string */
String. toserialize = function (OBJ ){
VaR ransfercharforjavascript = function (s ){
VaR newstr = S. Replace (
/[\ X26 \ x27 \ x3c \ x3e \ x0d \ x0a \ x22 \ x2c \ x5c \ x00]/g,
Function (c ){
ASCII = C. charcodeat (0)
Return '\ u00' + (ASCII <16? '0' + ASCII. tostring (16): ASCII. tostring (16 ))
}
);
Return newstr;
}
If (OBJ = NULL ){
Return null
}
Else if (obj. constructor = array ){
VaR builder = [];
Builder. Push ("[");
For (VAR index in OBJ ){
If (typeof OBJ [Index] = "function") continue;
If (index> 0) builder. Push (",");
Builder. Push (string. toserialize (OBJ [Index]);
}
Builder. Push ("]");
Return builder. Join ("");
}
Else if (obj. constructor = Object ){
VaR builder = [];
Builder. Push ("{");
VaR Index = 0;
For (var key in OBJ ){
If (typeof OBJ [Key] = "function") continue;
If (index> 0) builder. Push (",");
Builder. Push (string. Format ("\" {0} \ ": {1}", key, String. toserialize (OBJ [Key]);
Index ++;
}
Builder. Push ("}");
Return builder. Join ("");
}
Else if (obj. constructor = Boolean ){
Return obj. tostring ();
}
Else if (obj. constructor = Number ){
Return obj. tostring ();
}
Else if (obj. constructor = string ){
Return string. Format ('"{0}"', ransfercharforjavascript (OBJ ));
}
Else if (obj. constructor = Date ){
Return string. format ('{"_ datatype": "date", "_ thisue": {0}', obj. gettime ()-(new date (1970, 0, 1, 0, 0 )). gettime ());
}
Else if (this. tostring! = Undefined ){
Return string. toserialize (OBJ );
}
}
Jquery asynchronous request:Copy codeThe Code is as follows: $ (function (){
/* Click the event button */
$ ("# Btn_post_test"). Click (function (){
VaR DATA = [
{Userid: "11", Username: {firstname: "323", lastname: "2323"}, keys: ["Xiaoming", "Xiaohong"]},
{Userid: "22", Username: {firstname: "323", lastname: "2323"}, keys: ["Xiaoming", "Xiaohong"]},
{Userid: "33", Username: {firstname: "323", lastname: "2323"}, keys: ["Xiaoming", "Xiaohong"]}
];
$. Post ("home/test", {users: String. toserialize (data)}, function (text ){
Alert (string. toserialize (text ));
}, "JSON ");
});
});
Click the button to submit the data and monitor the browser. You can find that the submitted data is the serialized content of the json object: Copy code The Code is as follows: Post/home/test HTTP/1.1
X-requested-with: XMLHttpRequest
Accept-language: ZH-CN
Referer: http: // localhost: 3149/test.html
Accept: Application/JSON, text/JavaScript ,*/*
Content-Type: Application/X-WWW-form-urlencoded
Accept-encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; slcc2 ;. net CLR 2.0.50727 ;. net CLR 3.5.30729 ;. net CLR 3.0.30729; Media Center PC 6.0; infopath.2 ;. net4.0c ;. net4.0e)
HOST: localhost: 3149
Content-Length: 501
Connection: keep-alive
Cache-control: No-Cache
COOKIE: cookiegloballoginuserid = 16063
Users = % 5B % 7b % 22 userid % 22% 3A % 2211% 2C % 22 name % 22% 3A % 7b % 22 firstname % 22% 3A % 22% 2C % 22 lastname % 22323% 3A % 222323% 22% 7D % 2C % 22 keys % 22% 3A % 5B % 22 Xiaoming % 22% 2C % 22 Xiaohong % 22% 5d % 7D % 2C % 7b % 22 userid % 22% 3A % 2222% 22% 2C % 22 name % 22% 3A % 7b % 22 firstname % 22% 3A % 22323% 2C % 22 lastname % 22% 3A % 22% 7D % 2C % 22 keys % 222323% 3A % 5b % 22 Xiaoming % 22% 2C % 22 Xiaohong % 22% 5d % 7D % 2C % 7b % 22 userid % 22% 3A % 2233% 22% 2C % 22 name % 22% 3A % 7b % 22 firstname % 22% 3A % 22323% 22% 2C % 22 lastname % 22% 3A % 222323% 7D % 2C % 22 keys % 22% 3A % 5B % 22 Xiaoming % 22% 2C % 22 Xiaohong % 22% 5d % 7D % 5D
Second, bind the backend server's processing parameters: Copy code The Code is as follows: using system. Collections. Generic;
Using system. Web. MVC;
Using newtonsoft. JSON;
Using newtonsoft. JSON. LINQ;
Namespace WebOS. Controllers
{
[Handleerror]
Public class homecontroller: Controller
{
/// <Summary>
/// Test Method
/// </Summary>
/// <Param name = "users"> User Data </param>
/// <Returns> submitted user group </returns>
Public actionresult test ([modelbinder (typeof (jsonbinder <user>)] list <user> Users)
{
Return JSON (users, jsonrequestbehavior. allowget );
}
}
/// <Summary>
/// Object entity
/// </Summary>
[Jsonobject]
Public class user
{
[Jsonproperty ("username")]
Public username name {Get; set ;}
[Jsonproperty ("userid")]
Public String userid {Get; set ;}
[Jsonproperty ("keys")]
Public list <string> keys {Get; set ;}
}
/// <Summary>
/// Object entity
/// </Summary>
[Jsonobject]
Public class Username
{
[Jsonproperty ("firstname")]
Public String firstname {Get; set ;}
[Jsonproperty ("lastname")]
Public String lastname {Get; set ;}
}
/// <Summary>
/// JSON Data Binding class
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
Public class jsonbinder <t>: imodelbinder
{
Public object bindmodel (controllercontext, modelbindingcontext bindingcontext)
{
// Obtain submitted parameter data from the request
VaR JSON = controllercontext. httpcontext. Request. Form [bindingcontext. modelname] as string;
// The submit parameter is an object
If (JSON. startswith ("{") & JSON. endswith ("}"))
{
Jobject jsonbody = jobject. parse (JSON );
Jsonserializer JS = new jsonserializer ();
Object OBJ = Js. deserialize (jsonbody. createreader (), typeof (t ));
Return OBJ;
}
// The submit parameter is an array.
If (JSON. startswith ("[") & JSON. endswith ("]")
{
Ilist <t> List = new list <t> ();
Jarray jsonrsp = jarray. parse (JSON );
If (jsonrsp! = NULL)
{
For (INT I = 0; I <jsonrsp. Count; I ++)
{
Jsonserializer JS = new jsonserializer ();
Object OBJ = Js. deserialize (jsonrsp [I]. createreader (), typeof (t ));
List. Add (t) OBJ );
}
}
Return list;
}
Return NULL;
}
}
}
The front-end obtains the data returned by the backend. The result is the data submitted by the user:
The newtonsoft. JSON component is used for background JSON deserialization. For more information, see: http://james.newtonking.com/