Ajax Learning Series 11: server-side JSON

Source: Internet
Author: User
Tags php template

In a recent article in this series, you have learned how to convert JavaScript objects into JSON format. This format is easy to send (and receive) data that corresponds to an object or even an object array. In the last article in this series, you will learn how to handle
The data sent to the server in the same format and how to reply to the script in the same format.
Real Value of JSON

As described in the previous article in this series, 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 server

It is not difficult to send JSON to the server, but it is crucial and there are some important options to do. However, once you decide to use JSON, these options will be very simple and limited, so there are not many things to consider and focus on. It is important to be able to send the JSON string to the server, and it is best to do it as soon as possible and as simple as possible.

Use get to send JSON data with name/value pairs

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. php? People = "+ people. tojsonstring ();
XMLHTTP. Open ("get", URL, true );
XMLHTTP. onreadystatechange = updatepage;
XMLHTTP. Send (null );

This looks good, but 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. php? 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:

1. 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.
2. 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.

Send JSON data using post requests

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 ());

You have seen most of the Code in "Mastering Ajax, Part 1: Advanced requests and responses in Ajax". I should be familiar with it. Part 2 focuses on how to send post requests. The request is opened using post instead of get, and 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 now, just as it
The same result is obtained in the 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.

JSON is just text

Whether get or post is used, the key is that JSON is only text. Because no special encoding is required and each server-side script can process text data, JSON can be easily used and applied to the server. If JSON is in binary format or some weird text encoding, the situation is not that simple. Fortunately, JSON is only the regular text data (just as the data that the script can receive from form submission, as can be seen in the post segment and Content-Type headers), you do not have to worry too much when sending data to the server.

Explain JSON on the server

Once you have compiled the client JavaScript code, allowed users to interact with web forms and web pages, and collected the information required for processing sent to the server program, the server becomes the main character of an application (if an Asynchronous Server program is called, it may be a so-called "Ajax application. At this time, your selection on the client (for example, using a JavaScript Object and then converting it into a JSON string) must match the selection on the server side, for example, which API is used to decode JSON data.

Two steps for processing JSON

Regardless of the language used on the server, two steps are required to process JSON on the server.

1. Find the corresponding JSON parser/toolbox/helper API for the language used to compile the server program.
2. 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 above is about what we should know. Next, we will introduce each step in detail.

Search for the JSON parser

The best resource for finding a JSON parser or toolbox is the JSON site. 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 ).

For example, if you are using PHP, you can simply upgrade it to PhP 5.2 and use it to complete the operation. The latest version of PHP contains the JSON extension by default. In fact, it is also the best way to process JSON when using PHP. If Java Servlet is used, the org. JSON package on json.org is obviously a good choice. In this case, you can download json.zip from the JSON web site and add the included source files to the Project Build directory. After these files are compiled, everything is ready. The same procedure can also be used for other Supported languages. The language you use depends on your proficiency in the language, and it is best to use the language you are familiar.

Use the JSON parser

Once the available resources of the program are obtained, the only thing left is to find the appropriate method for calling. For example, suppose PHP uses a JSON-PHP template:

// This is just a code fragment from a larger PHP server-side script
Require_once ('json. php ');

$ JSON = new services_json ();

// Accept post data and decode it
$ Value = $ JSON-> decode ($ globals ['HTTP _ raw_post_data ']);

// Now work with value as raw PHP

This template can be used to convert all the obtained data (array format, multiline, single-value, or any content in the JSON Data Structure) to the native PHP format, put it in the $ value variable.

If the servlet uses the org. JSON package, the following code is used:

Public void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {

Stringbuffer JB = new stringbuffer ();
String line = NULL;
Try {
Bufferedreader reader = request. getreader ();
While (line = reader. Readline ())! = NULL)
JB. append (line );
} Catch (exception e) {// report an error}

Try {
Jsonobject = new jsonobject (JB. tostring ());
} Catch (parseexception e ){
// Crash and burn
Throw new ioexception ("error parsing JSON request string ");
}

// Work with the data using methods like...
// Int someint = jsonobject. getint ("intparamname ");
// String somestring = jsonobject. getstring ("stringparamname ");
// Jsonobject nestedobj = jsonobject. getjsonobject ("nestedobjname ");
// Jsonarray arr = jsonobject. getjsonarray ("arrayparamname ");
// Etc...
}

Conclusion

At this point, you should have a basic understanding of how to process JSON on the server. This article, in Part 2 of this series, not only provides technical help, but also shows you how flexible and powerful JSON is. Even if you don't use JSON in every application, the toolbox of excellent Ajax and JavaScript programmers always has no need for JSON.

Of course, I would like to share your JSON usage experience and the language in which you are more adept at processing JSON data on the server. You can visit Java and XML newsgroups (for links, see references) to contact me. Enjoy JSON and text data formats.

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.