Explanation of json mutual transfer between front and backend _ json

Source: Internet
Author: User
This article describes how to implement mutual data transfer between the frontend and backend in json format. For more information, see the mutual data transfer between the frontend and backend. If there are too many values, it is difficult to write and error-prone. Here we have sorted out a set of methods to pass values using tag attributes. The background values and front-end binding are greatly simplified.

1. convert a json object to a string

The Code is as follows:


$. Extend ({
// Convert a json object to a string [it seems that jquery does not provide this method]
ToJSONString: function (object ){
If (object = null)
Return;
Var type = typeof object;
If ('object' = type ){
If (Array = object. constructor) type = 'array ';
Else if (RegExp = object. constructor) type = 'regexp ';
Else type = 'object ';
}
Switch (type ){
Case 'undefined ':
Case 'unknown ':
Return;
Break;
Case 'function ':
Case 'boolean ':
Case 'regexp ':
Return object. toString ();
Break;
Case 'number ':
Return isFinite (object )? Object. toString (): 'null ';
Break;
Case 'string ':
Return '"' + object. replace (/(\ | \ ")/g," \ $1 "). replace (/\ n | \ r | \ t/g, function (){
Var a = arguments [0];
Return (a = '\ n ')? '\ N': (a =' \ R ')? '\ R': (a =' \ t ')? '\ T ':""
}) + '"';
Break;
Case 'object ':
If (object = null) return 'null ';
Var results = [];
For (var property in object ){
Var value = $. toJSONString (object [property]);
If (value! = Undefined) results. push ($. toJSONString (property) + ':' + value );
}
Return '{' + results. join (',') + '}';
Break;
Case 'array ':
Var results = [];
For (var I = 0; I <object. length; I ++ ){
Var value = $. toJSONString (object [I]);
If (value! = Undefined) results. push (value );
}
Return '[' + results. join (',') + ']';
Break;
}
}
});

2. Create a data container object [used to bind the foreground control value to be passed to the background]

The Code is as follows:


Var DataClass = {
Create: function (){
Return function (){
This. MyInit. apply (this, arguments); // create the object's constructor // The system name of the arguments parameter set cannot be written incorrectly
}
}
}
Var MyDataPack = DataClass. create ();
MyDataPack. prototype = {
// Initialization
MyInit: function (url, operation, params ){
This. data = new Object (); // all data capacity
Var bdata = new Object ();
Bdata. url = url; // address
Bdata. operation = operation; // operation
Bdata. params = params; // Parameter
This. data. BasicData = bdata; // basic data
},
// Add data such as addValue ("obj", "111 ");
AddValue: function (p, obj ){
This. data [p] = obj;
},
// Obtain the values of all tag controls and write data
GetValueSetData: function (togName ){
Var values = Object (); // a set of values
$ ("[Subtag = '" + togName + "']"). each (function (){
// For an input control
If (this. localName = "input "){
// For the text Control
If (this. type = "text" | this. type = "hidden "){
Values [this. id] = this. value;
}
Else if (this. type = "..."){
}
//......
}
Else if (this. localName = "..."){
}
//................
});
This. data [togName] = values; // Add to data set
},
// The value is getValue ("BasicData ")
GetValue: function (p ){
Return this. data [p];
},
// Obtain or set the url
GetUrl: function (url ){
If (url)
This. data. BasicData ["url"] = url;
Else
Return this. data. BasicData ["url"];
}
,
// Convert the value to the object data of the string
GetJsonData: function (){
Return $. toJSONString (this. data );
}
}

3. Create and bind a foreground data object [used to read the value passed by the background and bind it to the foreground Page]

The Code is as follows:


Var MyDataBinder = {
// Bind data to the control data: data tag: tag
Bind: function (data, Tag ){
Var MJson = $. parseJSON (data );
// Only tags marked are bound.
$ ("[Bindtag = '" + Tag + "']"). each (function (){
If (this. localName = "input "){
If (MJson [this. id]) // if the value is passed in the background
$ (This). attr ("value", MJson [this. id]);
}
Else if (this. localName = "..."){
}
//....
});
}
};

Iv. Example

Foreground html:

The Code is as follows:













I II 3.

Front-end js:

The Code is as follows:


// ================================================= ======================================
Var MyDataPack = new MyDataPack ("Handler1.ashx", "CESHI ","");
MyDataPack. getValueSetData ("subtag"); // write the control data to the object "subtag" as the tag to take the Control Value
// ------------------- Pass the foreground value to the background ---------------
$. Post (MyDataPack. getUrl (), MyDataPack. getJsonData (), function (data ){
// ------------------- Bind the background value to the foreground -----------------
MyDataBinder. Bind (data, "bind"); // "bind" is the tag of the control to be bound.
});

Background:

The Code is as follows:


Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
// ============================================== ====================================
// Because the converted json object string is passed in the background, all data is passed as a parameter.
Var values = context. Request. Form [0];
// The assembly System. Web. Extensions. dll needs to be introduced.
JavaScriptSerializer _ jsSerializer = new JavaScriptSerializer ();
// Convert the json object string to a Dictionary object
Dictionary > Dic = _ jsSerializer. Deserialize >>( Values );
// Now the dic contains all the values passed from the front-end.
String inp_2 = dic ["subtag"] ["inp_2"]; // you can directly obtain the value of the control whose id is inp_2 on the foreground page.
// ======================================================= ====================================
Dictionary Dic2 = new Dictionary ();
Dic2.Add ("inp_1", "Modify 1"); // only use the corresponding control id to pass the value here.
Dic2.Add ("inp_2", "Modify 2 ");
Dic2.Add ("inp_3", "Modify 3 ");
Context. Response. Write (_ jsSerializer. Serialize (dic2 ));
}

Do you know clearly about the use of json to implement value transfer in front and back end? If you have any questions, leave a message for me.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.