Ajax Learning (6)-server scripts and programs use JSON for response and response

Source: Internet
Author: User

 

JSON is a valid format for Ajax applications because it enables fast conversion between JavaScript objects and string values. Because Ajax applications are suitable for Sending plain text to server programs and receiving plain text, it is more desirable to generate text APIs than to generate text, JSON allows you to process local JavaScript objects without worrying about how to express them.
XML can also provide similar text benefits, but several existing APIs used to convert JavaScript objects into XML are not as mature as json apis; sometimes, you must exercise caution when creating and processing Javascript objects to ensure that the processing can work with the selected XML session API. But for JSON, the situation is very different: it can process almost all possible object types, and will return you a very good JSON data representation.
Therefore, the biggest value of JSON is that javascript can be processed as JavaScript rather than as a data format language. All the techniques you have learned about using JavaScript objects can be applied to your code without worrying about how to convert these objects into text. After that, you can call the following simple JSON method:

String myobjectinjson = myobject. tojsonstring ();

Now you can send the result text to the server.

* Send JSON to the server
---- Send JSON data with name/value pairs through get

The simplest way to send JSON data to the server is to convert it into text and then send it as the value of the name/value pair. It is important to note that the data in JSON format is a fairly long object and may appear as shown in Listing 1:
Listing 1. Simple JavaScript objects in JSON format

VaR people = {"programmers": [{"firstname": "Brett", "lastname": "McLaughlin ",
"Email": "brett@newInstance.com" },{ "firstname": "Jason", "lastname": "Hunter ",
"Email": "jason@servlets.com" },{ "firstname": "elliotte", "lastname": "Harold ",
"Email": "elharo@macfaq.com"}], "Authors": [{"firstname": "Isaac ",
"Lastname": "Asimov", "genre": "Science Fiction" },{ "firstname": "tad ",
"Lastname": "Williams", "genre": "Fantasy" },{ "firstname": "Frank ",
"Lastname": "Peretti", "genre": "Christian fiction"}], "musicians ":[
{"Firstname": "Eric", "lastname": "Clapton", "instrument": "Guitar "},
{"Firstname": "Sergei", "lastname": "Rachmaninoff", "instrument": "Piano"}]}
 
If you want to send a name/value pair to the server, it should be as follows:

VaR url = "organizepeople. aspx? People = "+ people. tojsonstring ();
XMLHTTP. Open ("get", URL, true );
XMLHTTP. onreadystatechange = updatepage;
XMLHTTP. Send (null );

There is a problem: there are spaces and various characters in JSON data, and Web browsers often have to try to compile it. To ensure that these characters do not cause confusion on the server (or when sending data to the server), add the following in the Javascript escape () function:

VaR url = "organizepeople. aspx? People = "+ escape (people. tojsonstring ());
Request. Open ("get", URL, true );
Request. onreadystatechange = updatepage;
Request. Send (null );

This function can process spaces, diagonal lines, and any other content that may affect the browser and convert them into available web characters (for example, spaces are converted to % 20, the browser will not treat it as a space, but will not change it and pass it directly to the server ). Then, the server will (usually automatically) convert them back to their original "face" after transmission ".

There are two disadvantages of this practice:
The URL string length is limited when a GET request is used to send large data blocks. Although this restriction is broad, the length of the object's JSON string representation may exceed your imagination, especially when using extremely complex objects.
When sending all data in plain text across networks, the security of data transmission exceeds your processing capability.
In short, the above are two restrictions on GET requests, not two simple things related to JSON data. When you want to send more content beyond the user name and surname, such as the selection in the form, you may need to pay more attention to the two. To process any confidential or extremely long content, you can use post requests.

---- Use the POST request to send JSON data

When you decide to use the POST request to send JSON data to the server, you do not need to make a lot of changes to the Code, as shown below:

VaR url = "organizepeople. php? Timestamp = "+ new date (). gettime ();
Request. Open ("Post", URL, true );
Request. onreadystatechange = updatepage;
Request. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
Request. Send (people. tojsonstring ());

Use post instead of get to open the file. The Content-Type header is set to let the server know what data it can get. In this case, it is application/X-WWW-form-urlencoded, which allows the server to know that the text is sent, just as it gets from the regular HTML form.
Another simple prompt is the append time at the end of the URL. This ensures that the request will not be cached after it is sent for the first time, but will be re-created and re-issued after each call of this method; the URL varies slightly depending on the timestamp. This technique is often used to ensure that a new request is generated every time a script post is sent, and the Web server does not try to cache responses from the server.

* Explain JSON on the server
Two steps for JSON processing:
Find the corresponding JSON parser/toolbox/helper API for the language used to write the server-side program.
Use the JSON parser/toolbox/helper API to retrieve request data from the client and convert the data into something that the script can understand.

The best resource for finding a JSON parser or toolbox is the JSON site (for links, see references ). In addition to understanding all aspects of the format itself, you can also find various JSON tools and Resolvers through various links, from ASP to Erlang, to Pike, and then to Ruby, everything. You only need to download the toolbox for the language used to write your own scripts. To enable server scripts and programs to use this toolkit, you can select, expand, or install it as needed (if C #, PHP, or lisp is used on the server, is more variable ).

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.