AJAX (four) example--JSON format data

Source: Internet
Author: User
Tags httpcontext javascript array

This issue explains the use of JSON-formatted data in Ajax. But let's not talk about JSON, let's start with a case, and then we'll talk about why we use JSON data and how to use it.

First, Case

Very classic, but also very simple Ajax case, the provinces and cities linkage. It is common on the Internet to select a province and then dynamically load the city options contained in the selected province in the <select> tag of the city.

HTML is extremely simple. To make the case easier, the options in the <select> tab of the province are written dead, where value represents the province's primary key ID. The same is true of the <select> tag of the city, not to repeat it.

<body>Province:<SelectId="Province"> <option value="1"> Hebei </option> <option value="2"> Henan </option> <option value="3"> Shandong </option> <option value="4"> Shanxi </option> </Select>City:<SelectId=" City"></Select></body>

  The background code is also very simple, still using the general handler, as follows.

Where City is a municipal entity class, 3 fields.

A simple explanation is the general handler, and the idea is to:

1. Obtain the proid (province ID) passed to the GET request via QueryString.

2. Obtain the included City (ilist<city>) from the database according to Proid.

3. Traverse this ilist<city> City collection and then spell it similar to "<option value= ' 0100001 ' > Chengdu </option><option value= ' 0100002 ' > Mianyang </option>, ... "Such a string. Because such a string can be placed directly inside the <select> tag pair, the option to form the drop-down option box.

 Public classcity{ Public intId {Get;Set; }//City Primary Key     Public stringName {Get;Set; }//City Name     Public intproid {Get;Set; }//ID of the province}
Public classcityshandler:ihttphandler{ Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain"; if(Context. Request.HttpMethod.ToUpper () = ="GET") { stringProid = context. request.querystring["proid"]; Citys citys=NewCitys (); IList<City> cList =Citys. Getcitysbyproid (proid); StringBuilder opts=NewStringBuilder (); foreach(City CinchcList) {opts. Append ("<option value= '"+ C.id +"' >"); OPTs. Append (C.name); OPTs. Append ("</option>"); } context. Response.Write (opts. ToString ()); } } Public BOOLisreusable {Get { return false; } }}

  Next is the client code. When the user selects any of the provinces, the onchange event that triggers the province drop-down box is used in this event to make a GET request to access the server-side CITYSHANDLER.ASHX using AJAX mode. The code is as follows:

The code does not have much to explain, because the service side directly returned is the concatenation of good HTML tag strings, so directly as innerHTML into the <select id= "city" ><select> to go on it, it is very simple.

<script>window.onload=function () {        varSelprov = document.getElementById ("province"); Selprov.onchange=function () {            if(window. XMLHttpRequest) {XHR=NewXMLHttpRequest (); }            Else{XHR=NewActiveXObject ("Microsoft.XMLHTTP"); }            varProid = This. Value; varurl = "Cityshandler.ashx" + "proid=" +proid; Xhr.open ("Get", url,true); Xhr.setrequestheader ("If-modified-since", "0"); Xhr.onreadystatechange=function () {                if(Xhr.readystate = = 4 && xhr.status = 200) {                    varopts =Xhr.responsetext; varSelcity = document.getElementById ("City"); Selcity.innerhtml=opts; }} xhr.send (NULL); }    }</script>
second, the drawbacks

Although the function is realized, but the disadvantage is quite big.

1. The string returned by the server contains not only the data that needs to be shown to the user, such as the city name, the city ID, and more importantly, the data is wrapped in a <option> tag. In other words, the data returned by the server is dirty, or not purely, loaded with too many HTML tags. The disadvantage of this is that the backend data interface is limited to dead, because <option> can only be placed in the <select> tag as an option, then if the customer wants to display all the data in a <table>, Then this backend service is not reusable.

2. With a lot of HTML tags, the amount of data to be transferred must be increased, so it is bound to reduce the performance of the program, at least the client's response speed will be slow, which is unacceptable to the performance control freak.

iii. Improvement of--json

 JSON is just a data format that evolves from the literal notation of JavaScript and is an object description in the JavaScript language. Its syntax is particularly simple: {"Key1": "Val1", "Key2": "Val2", ...}. The only difference between it and literal notation is that the JSON format requires that all keys and value be enclosed in double quotation marks, and the single quotation mark is not allowed.

  OK, let's look at the service-side code transformation. Just look at the general process of the PR method is OK .

Here the System.Web.Script.Serialization.JavaScriptSerializer is used to serialize a set, and the result of serialization is of course a JSON-formatted string.  

 public void   ProcessRequest (HttpContext Context) {context.    Response.ContentType  = "Text/plain" ;  if  (context. Request.HttpMethod.ToUpper () = = "GET"  = context.        request.querystring["proid" ];        Citys citys  = new   Citys (); IList  <City> cList = Citys.        Getcitysbyproid (proid); System.Web.Script.Serialization.JavaScriptSerializer JSS  = new   System.Web.Script.Serialization.JavaScriptSerializer (); String Jsoncitys  = JSS.        Serialize (cList); Context.    Response.Write (Jsoncitys); }}

  ★ It is important to note that JSON objects are inherently different from JSON-formatted strings.

To make an analogy:

int i = 12345;

String str = "12345"; it appears to be 12345, but it is essentially different, the variable i is an integer that can do arithmetic, and the data in the variable str appears to be "12345", but it is a string and cannot do arithmetic.

If you don't understand it, look at an example.

Int[] arr = {22, 12, 34, 45}; Obviously, this is a plastic array.

"{22, 12, 34, 45}", and this is a string, just like the top of the array "grow" very much.

So here we go. NET provided by the JavaScriptSerializer serialized data, is a string, looks like "[{" Id ": 1," "Name": "Chengdu", "proid": 5},{"Id": 2, "Name": "Mianyang", "proid" : 5},{"Id": 3, "Name": "Guangyuan", "Proid": 5}] "This looks like this. But watch out, there are "" at both ends, this is a solemnity string, so when this data is passed to the front end, we need to use JavaScript to convert the string to a JSON object.

  Next, transform the foreground JavaScript code

  You just have to look at the callback function, and there's no need to change it anywhere else.

Xhr.onreadystatechange =function () {    if(Xhr.readystate = = 4 && xhr.status = 200) {        varopts =Xhr.responsetext; varSelcity = document.getElementById ("City"); //selcity.innerhtml = opts;        varJsoncitys =Json.parse (opts);  for(vari = 0; i < jsoncitys.length; i++) {            varopt = document.createelement ("option")); Opt.setattribute ("Value", Jsoncitys[i].            ID); Opt.innerhtml=Jsoncitys[i].            Name;        Selcity.appendchild (opt); }}}xhr.send (NULL);

The key point is this statement: var jsoncitys = Json.parse (opts); Json.parse () is the 1 API provided by JavaScript, which is the function of converting a JSON-formatted string into a JSON object. Of course, if the string passed in is a string of array styles composed of multiple JSON-formatted objects, as we have here: "[{" id ": 1," Name ":" Chengdu "," proid ": 5},{" Id ": 2," Name ":" Mianyang "," Proid ": 5},{" Id ": 3," Name ":" Guangyuan "," Proid ": 5}]". We get the data from the background, the quotation marks inside the first is a pair of [], this square bracket is clearly the symbol of the array in JS.

In this case, Json.parse () parses the string into a JavaScript array consisting of multiple JSON objects. Then we can iterate through it with a for loop.

The next DOM operation does not have to be elaborate.

Looking back at this example, after the transformation, the background is passed the data is "pure", without any presentation layer of things, this brings the benefits: 1. The amount of data to be transmitted is small and lightweight. 2. More conducive to the presentation layer in accordance with a variety of requirements to show, show layer how to play on how to play. Cool!

AJAX (four) example--JSON format data

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.