JSON advanced 4-The beauty of frontend and backend Interaction

Source: Internet
Author: User
Tags tojson

For example, in the past, we had to write a lot of things on the registration interface. At the front end, we had to use various text input boxes, and some also used select and checkbox to provide users with various information, whether in JSP or APs. net, we need to make one-to-one correspondence between the foreground text box and the background assignment. A few of them are okay. Even a dozen of them can handle the problem. Even a few of them are boring. What I do not like most is to do this kind of things. Once you want to add something, you need to modify the HTML and backgroundCodeThe form submission method is good. It is troublesome to use Ajax. Besides modifying the background code and JS Code, the coupling degree is very high. The following example shows some of my new programming experiences, use JSON to solve this problem.

Here I used four JS files including Jquery-1.2.6 :( if you are not very familiar with JQ, you can see some other garden friends writeArticle)

Introduce the other three:

Json2.js is a JS written by a foreigner to convert JSON and string (it seems like something in ext, but I found it in a foreigner's blog ). I have made some extensions for it. Let's talk about it later.

Json2.parse (); // converts a JSON string to a JSON object (including a JSON array ).

Json2.stringify (); // converts a JSON object into a JSON string (including a JSON array ).

Validator. JS is a JS file for data verification. I use it in many places in my daily work. It is a simple verification written by myself. If you are interested, you can extend it to him. I provide date, array, Chinese, and other verification methods.

Tableserializer. JS converts the elements in the table into JSON and JSON to the table. This JS is not perfect yet. If you are interested, you can extend it, or tell me your needs and I will continue to improve it.

Tableserializer. tabletojson (); // converts the items in the table to a JSON array.

Tableserializer. jsontotable (); // converts a JSON array to an element in the table.

Example: (if you are interested, you can enter the information to perform operations)


PSTS AllChinaUSAJapan
PSTS AllChinaUSAJapan

Conversion

PSTS AllChinaUSAJapan
PSTS AllChinaUSAJapan

Corresponding to tableserializer, which must conform to the HTML structure:

< Table ID = "Tab" >
< Tr >
< TD Type = "Text" >
< Div Type = "Text" >
< Input Type = "Text" MSG = "*" Key = "Guid" Datatype = "Ints" />
</ Div >
</ TD >
< TD Type = "Checkbox" >
< Div Type = "Checkbox" >
PSTS < Input Type = "Checkbox" Key = "PSTS" Datatype = "Int" />
</ Div >  
</ TD >
< TD >
< Div Type = "Select" >
< Select MSG = "*" Key = "GJ" Datatype = "String" >
< Option Value = "" > All </ Option >
< Option Value = "China" > China </ Option >
< Option Value = "USA" > USA </ Option >
< Option Value = "Japan" > Japan </ Option >
</ Select >
</ Div >  
</ TD >
< TD >
< Div Type = "Text" >
< Input Type = "Text" MSG = "*" Key = "DT" Datatype = "Date" />
</ Div >
</ TD >
</ Tr >
</ Table >

 

As you can see, each operation item that gets the value is nested with a div class. This type of Div has a special attribute type, which indicates the type of the Operation item HTML.

The operation item has a key attribute. The value of this attribute represents the JSON primary key value, and the datatype represents the data type, MSG indicates the error message prompted when the data input type fails verification.

JS Code:

< Script >
VaR Tab;
$ (Document). Ready (
Function (){
// Construct a new JSON object of tableserializer, and convert the specified table to a JSON array with the ID of 'tab '.
Tab = $. Extend ({}, tableserializer, {IDs: ' # Tab ' });
}
);
Function A (){
// Obtain the string in JSON array format specified in the table with ID as tab.
VaR Str = Tab. tabletojson ();
// Determine whether data type verification is passed.
If (Tab. isallow ){
// Assign JSON to HTML items in the table with ID fa.
Tableserializer. jsontotab ( " # Fa " , Json2.parse (STR ));
}
}
< / SCRIPT>

So far, we have not seen the interaction between JSON and the background.

In fact, it is very simple. We only need to send the background strings in the JSON array format obtained in the tabletojson () method.

Here I used newtonsoft. JSON, an open-source project in C:

The background statement is as follows:

Namespace Webapplication1
{
Public   Partial   Class _ Default: system. Web. UI. Page
{
Protected   Void Page_load ( Object Sender, eventargs E)
{
// Here I am using Ajax. the backend obtains a string in the JSON array format passed by the front end.
If ( ! String . Isnullorempty (request [ " Key " ]) {
// Deserialization
List < SS > Sss = (List < SS > ) Javascriptconvert. deserializeobject (request [ " Key " ], Typeof (List < SS > ));
// In the serialization to the foreground.
Response. Write (SSS. tojson ());
Response. End ();
}
}
}
// The entity that corresponds to the content input at the front-end.
Public   Class SS {
Public   Int Guid;
Public   Bool PSTS =   True ;
Public   String Gj =   String . Empty;
Public Datetime DT;
}
// Serialize an object into a JSON string
Public   Static   Class Jsonhelper
{
Public   Static   String Tojson ( This   Object OBJ)
{
Stringwriter SW =   New Stringwriter (system. Globalization. cultureinfo. invariantculture );
Newtonsoft. JSON. jsonserializer JSON =   New Newtonsoft. JSON. jsonserializer ();
JSON. nullvaluehandling = Newtonsoft. JSON. nullvaluehandling. Ignore;
JSON. referenceloophandling = Newtonsoft. JSON. referenceloophandling. Ignore;
Using (Newtonsoft. JSON. jsonwriter JW =   New Newtonsoft. JSON. jsontextwriter (SW ))
{
JSON. serialize (JW, OBJ );
}
Return Sw. tostring ();
}
}
}

 

It is not hard to see that no matter how the demand changes, we only need to change the background entity and the foreground HTML, without making any changes to the foreground JS and background code.

Sample Code

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.