JSON-based Ajax Development

Source: Internet
Author: User
This article explains how to use Ajax and JSON analyzer to create a complex JSON data transmission layer between the client and the server.

  I. Introduction

There is no doubt that Ajax has become a powerful user interaction technology in today's web development, but its many possibilities of application are still little known. In this article, we will discuss how to use the JavaScript Object flag (JSON) and JSON analyzer to create a complex and powerful JSON Data Transmission Layer Between the server and the client Ajax engine. We will discuss in detail how to create a group of objects (often considered as a package in other languages) and how to serialize these objects into JSON to send them to the server, and how to convert the server-side JSON deserialization into a client-side JavaScript Object.

Tip: you can find the JSON analyzer used in this article on the Douglas crockford website.

Before proceeding, this article assumes that you have mastered javascript technology and understand how to create a basic Ajax engine, send requests to the server and receive responses from the server. To better understand the examples in this article, you need to download the corresponding source code file.

  Ii. Start

To further Abstract Our Ajax requests and help us share Ajax engine code among different applications in the future, this article uses an Ajax engine created by myself. To use this engine, we simply import three JavaScript files and send a request to an object named ajaxupdater. Then, the engine is responsible for processing other tasks, including sending the response proxy to the callback method specified in the request. The following example shows how to use this engine to send requests and import related files:

The following is a reference clip:
<SCRIPT type = "text/JavaScript" src = "javascript/model/ajax. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/model/HTTP. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/model/ajaxupdater. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
Document. load = ajaxupdater. Update ('get', URL, callback );
</SCRIPT>

First, let's discuss JavaScript objects.

Iii. Javascript objects

 

Javascript is often misunderstood in the past. It seems that it is mainly used to achieve the graphic effect on the client browser side. In fact, JavaScript is a powerful language, especially when it is combined with Ajax and the server side of an application; however, even on the client, javascript can also implement more functions than you expected. Object-oriented Javascript is an example. It allows us to create objects, expand internal objects, and even create our objects into packages for easier management.

In this example, we will create three objects: auto, car, and wheel. Each of them is a simple object. Here, we only use them to demonstrate how to create a basic package.

First, the auto object is declared as a new object:

The following is a reference clip:
VaR auto = new object ();

Note that this auto object will be used as the parent class of the car object. Therefore, the car object becomes an attribute of the auto object, but it is separated into another file for easier management (this concept is often used in other object-oriented languages, but it is not often mentioned in Javascript ). The following is the code of the car object:

The following is a reference clip:
Auto. Car = new object ();
Auto. Car. color = "# fff ";
Auto. Car. setcolor = function (_ color)
{
Auto. Car. Color = _ color;
}
Auto. Car. setcolor ("#333 ");

As you can see, this car object is a sub-object of the auto object-this is a class object hierarchy. This object has an attribute named color and a method for setting it. Here, we set the color attribute to gray to overwrite the default white color. Remember this fact when we serialize this object later.

The next object, wheel, is a child object of car:

The following is a reference clip:
Auto. Car. Wheel = new object ();
Auto. Car. Wheel. color = "#000 ";

Here, wheel is a basic object, but it shows another layer in the object hierarchy. This object has an attribute named "black" ("#000") by default.

Next, let's analyze why these objects are so important and how we use the simple properties they provide.

Iv. serialize JavaScript objects into JSON

 

With the help of the JSON analyzer, we can easily serialize the JavaScript Object just created into JSON. First, we need to download a copy of the analyzer and add it to the document. The following code is used to import the script in my example in this article:

The following is a reference clip:
<SCRIPT type = "text/JavaScript" src = "javascript/utils/jsonparser. js"> </SCRIPT>

I have added this analyzer to my JavaScript directory, that is, a subdirectory called utils.

The following is the final code snippet used to import the appropriate Javascript file:

The following is a reference clip:
<SCRIPT type = "text/JavaScript" src = "javascript/auto. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/car. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/wheel. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/utils/jsonparser. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/model/ajax. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/model/HTTP. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "javascript/model/ajaxupdater. js"> </SCRIPT>

After importing an appropriate file, we can simply add two DIV elements and an onload event to the HTML document to start serialization. The two DIV elements will have the ID: Body and loading respectively. The loading label is used by the Ajax engine to indicate the progress, and the body label is used to display messages.

The following is a reference clip:
<Div id = "loading"> </div>
<Div id = "body"> </div>

 

The onload event corresponds to the body element and sets its innerhtml attribute as a JavaScript Object (as a serialized JSON string ). To achieve this, I used the tojsonstring method in the jsonparser. js file on the auto object:

The following is a reference clip:
<Body onload = "document. getelementbyid ('body'). innerhtml = '<B> local objects serialized as JSON </B>
Auto object: '+ auto. tojsonstring (); ">

This Code uses the auto object and all its sub-objects, and serializes them into a JSON string using the tojsonstring method of the json analyzer. The data can then be used as a data exchange format on the server side.

You may still remember that we previously called a method called setcolor to change the color of the car object. At that time, I used it because I wanted to show you how serialization can be implemented at any point in the runtime, and also to reflect the latest data in the object.

If you carefully analyze the onload event, you will notice that the car and wheel objects are enclosed in square brackets, which represent the parent object (that is, auto ). This means that the serialized JavaScript Object can be sent to the server at runtime to store the latest data, you can also receive data from the server at application startup to retrieve most of the current data from the database. The most exciting part is that in order to create a "seamless" process, all data exchanges with the server can be implemented using JSON technology.

Next, let's take a look at how the same data is received from the server and how it is used to obtain the latest data (typically, from a database) serialized as a client JavaScript Object.

5. Convert JSON deserialization into a client JavaScript Object

 

In this article, I create a static file as a JSON response, but in actual development, you can store the data in a database and return it using a server language. With this capability, we can easily create a powerful data exchange process! We have analyzed this serialization process. With the basic Ajax experience, you should be able to understand how data is sent to the server. Now let's discuss the problem of deserialization. First, let's look at a static JSON file provided in this example. This file is actually serialized data in the previous section:

 

The following is a reference clip:
{& Quot; car & quot;: {& quot; color & quot;: & quot; #333 & quot;, & quot; Wheel & quot;: {& quot; color & quot;: & quot; #000 & quot "}}}

As an example of a request for a JSON file, when we click the following link, we will request this serialized auto object:


The following is a reference clip:
<A href = "javascript: ajaxupdater. Update ('get', 'json/data. js', displayresponse);"> get remote JSON </a>

Once a response message is received, our displayresponse callback method will be activated, and then we will be able to deserialize and start using these objects:

The following is a reference clip:
<SCRIPT type = "text/JavaScript">
Function displayresponse ()
{
If (Ajax. checkreadystate ('loading') = "OK ")
{
VaR auto = Ajax. Request. responsetext. parsejson ();
Document. getelementbyid ("body"). innerhtml + ="
<B> remote JSON unserialized </B> ";
Document. getelementbyid ("body"). innerhtml + ="
Car color: "+ auto. Car. color;
Document. getelementbyid ("body"). innerhtml + ="
Wheel color: "+ auto. Car. Wheel. color;
}
}
</SCRIPT>

This is an exciting part! Once we have this responsetext, we can simply use the parsejson method in the JSON analyzer to recreate our auto object from serialized data. With this new auto object, we can call the corresponding sub-objects. This feature allows us to send objects back and forth on servers and clients-without having to perform a lot of analysis work, but we have to do so in the case of standard XML responses in the past. In this way, we can create client JavaScript objects that can retain their status based on AJAX technology.

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.