Use JSON to accelerate Ajax

Source: Internet
Author: User

 

Use JSON to accelerate Ajax
By Sean Kelly

Source: http://blog.csdn.net/Jekeyhua/archive/2006/05/03/707257.aspx

After Microsoft added ActiveX XMLHTTP objects used to execute Javascript in IE, it seemed that Ajax was a revolutionary web application development. Today, Firefox, Safari, opera, and other browsers all provide XMLHttpRequest so that they can access colr.org, backpackit.com, maps.google.com. these websites have the same performance and feeling as other desktop applications, even though they run in browsers.

In Ajax, when a user views and interacts with a page, the page's JavaScript code requests data (Asynchronous in Ajax) to the web server "). These requests are HTTP requests, just like a browser getting a page in the first place, which can include any image or style sheet. Similarly, the XMLHTTPRequest object can also be used to obtain various types of data, not just XML. For example, JavaScript can use XMLHttpRequest to obtain a common text file from the Web server and display its content in a form.

The XMLHTTPRequest object looks for the Content-Type header at the data front end to analyze the MIME type of the data returned from the web server. For example, if the type is text/plain, you can access the text by checking the responsetext attribute of the XMLHTTPRequest object. However, if the type is text/XML, the XMLHTTPRequest object has a special step: it runs an XML parsing for the returned document and creates a Document Object Model (DOM) in the memory) tree to describe the document, so that the document is available in the responsexml attribute. Then, you can use the standard DOM method of JavaScript to manipulate this object tree and access each element, attribute, and other text in the tree.

XML is the standard method for data exchange, but it is usually not the best method. Although XML can add structures and metadata for data, it is indeed a troublesome method. XML also has a very complex syntax and requires a parser class to parse it. In JavaScript, XML must be parsed as a DOM tree for use. In addition, once a DOM tree is built, you have to create javascript objects or other methods to use XML data in client applications.

Fortunately, there is a better way.

Use JSON
JSON, also known as JavaScript Object Notation, is a lightweight syntax that describes data. JSON is elegant because it is a subset of the Javascript language. Next you will see why it is so important. First, compare the JSON and XML syntaxes.

Both JSON and XML use structured methods to describe data. For example, an address book application can provide Web Services for generating Address Cards in XML format:
<? XML version = '1. 0' encoding = 'utf-8'?>
<Card>
<Fullname> Sean Kelly </fullname>
<Org> SK consulting </org>
<Emailaddrs>
<Address type = 'work'> kelly@seankelly.biz </address>
<Address type = 'home' Pref = '1'> kelly@seankelly. TV </address>
</Emailaddrs>
<Telephones>
<Tel type = 'work' Pref = '1'> + 1 214 555 1212 </Tel>
<Tel type = 'fax'> + 1 214 555 1213 </Tel>
<Tel type = 'mobile'> + 1 214 555 1214 </Tel>
</Telephones>
<Addresses>
<Address type = 'work' format = 'us'> 1234 Main St
Springfield, TX 78080-1216 </address>
<Address type = 'home' format = 'us'> 5678 Main St
Springfield, TX 78080-1316 </address>
</Addresses>
<URLs>
<Address type = 'work'> http://seankelly.biz/</address>
<Address type = 'home'> http://seankelly. TV/</address>
</URLs>
</Card>

JSON format:

{
"Fullname": "Sean Kelly ",
"Org": "SK consulting ",
"Emailaddrs ":[
{"Type": "work", "value": "kelly@seankelly.biz "},
{"Type": "home", "Pref": 1, "value": "kelly@seankelly. TV "}
],
"Telephones ":[
{"Type": "work", "Pref": 1, "value": "+ 1 214 555 1212 "},
{"Type": "fax", "value": "+ 1 214 555 1213 "},
{"Type": "mobile", "value": "+ 1 214 555 1214 "}
],
"Addresses ":[
{"Type": "work", "format": "us ",
"Value": "1234 main stnspringfield, TX 78080-1216 "},
{"Type": "home", "format": "us ",
"Value": "5678 main stnspringfield, TX 78080-1316 "}
],
"URLs ":[
{"Type": "work", "value": "http://seankelly.biz /"},
{"Type": "home", "value": "http://seankelly. TV /"}
]
}

As you can see, JSON has structured nested data elements, which are similar to XML. JSON is also text-based, and XML is the same. Both use Unicode. JSON and XML are both easy to read. Subjectively, JSON is clearer and redundant. The JSON web site strictly describes the JSON syntax. This is the case currently. It is indeed a simple little language! XML is indeed suitable for marking documents, but JSON is an ideal format for data interaction. Each JSON document describes an object that contains nested objects, arrays, strings, numbers, Boolean values, or null values.

In the example code of these address cards, the JSON version is more lightweight and only occupies 682 bytes of space, while the XML version requires 744 bytes of space. Although this is not a considerable savings. The actual benefit comes from the parsing process.

XML comparison JSON: loss of status
By using the XMLHTTPRequest object, you can obtain XML and JSON files from your Ajax-based applications. The interaction code is as follows:

VaR Req = new XMLHttpRequest ();
Req. Open ("get", "http: // localhost/ADDR? Cardid = 32 ",/* async */true );
Req. onreadystatechange = myhandler;
Req. Send (/* No Params */null );
As a web server response, your processor function (myhandler function) is called multiple times, providing you with the opportunity to terminate transactions and update progress bars in advance. Generally, it takes effect only after the Web request is completed: At that time, you can use the returned data.

To process the address card data of the XML version, the myhandler code is as follows:

Function myhandler (){
If (req. readystate = 4/* Complete */){
// Update address field in a form with First Street address
VaR addrfield = Document. getelementbyid ('addr ');
VaR root = Req. responsexml;
VaR addrselem = root. getelementsbytagname ('address') [0];
VaR firstaddr = addrselem. getelementsbytagname ('address') [0];
VaR addrtext = fistaddr. firstchild;
VaR addrvalue = addrtext. nodevalue;
Addrfield. value = addrvalue;
}
}
It is worth noting that you do not have to parse the XML document: the XMLHTTPRequest object is automatically parsed and the DOM tree in responsexml is available. By using the responsexml attribute, you can call the getelementsbytagname method to find the document address. You can also use the first method to find the document address. Then, you can call getelementsbytagname again to find the first address element in the address section. This gets the first Dom sub-node of the document, which is a text node and obtains the value of the node. This is the street address you want. Finally, the results can be displayed in the form field.

It is really not a simple task. Now, try again with JSON:
Function myhandler (){
If (req. readystate = 4/* Complete */){
VaR addrfield = Document. getelementbyid ('addr ');
VaR card = eval ('+ Req. responsetext + ')');
Addrfield. value = card. Addresses [0]. value;
}
}
The first thing you do is parse the JSON response. However, because JSON is a subset of JavaScript, you can use the Javascript compiler to parse it and call the eval function. Only one line is required for parsing JSON! In addition, manipulating objects in JSON is like manipulating other JavaScript objects. This is obviously easier to manipulate than using the DOM tree, for example:
Card. Addresses [0]. value is the first street address, "1234 main STB &"
Card. Addresses [0]. type is the address type, "work"
Card. Addresses [1] is the home address object
Card. fullname is the name of card, "Sean Kelly"
If you take a closer look, you may find that the document in XML format has at least one heel element, card. This does not exist in JSON. Why? Probably, if you are developing JavaScript to access web services, you already know what you want. However, you can use the following in JSON:
{"Card": {"fullname ":...}}
With this technology, your JSON file always starts with an object with a single naming attribute, which identifies the object type.

Is JSON fast and reliable?
JSON Provides Lightweight small documents, and JSON is easier to use in JavaScript. XMLHttpRequest automatically parses the XML file for you, but you still need to manually parse the JSON file, but is it slower to parse JSON than to parse XML? After thousands of repeated tests, the author uses XMLHttpRequest to parse XML and JSON. The result is 10 times faster than XML! When Ajax is treated as a desktop application, speed is the most important factor. Obviously, JSON is better.

Of course, you cannot always control the server to generate data for Ajax programs. You can also use a third-party server to provide XML output instead of the server. In addition, if the server exactly provides JSON, are you sure you want to use it?

In the code, it is worth noting that you pass the response text directly to the eval. If you control the server, you can do this. If not, a malicious server can enable your browser to perform dangerous operations. In this case, you 'd better use the code written in JavaScript to parse JSON. Fortunately, this already exists.

Speaking of parsing, Python enthusiasts may note that JSON is not only a subset of JavaScript, but also a subset of Python. You can directly execute JSON in Python or use secure JSON resolution instead. The json.org website lists many common JSON parser.

Server-side JSON
Until now, you may focus on using JSON for Ajax-based Web applications running in your browser. Naturally, data in JSON format must be generated on the server. Fortunately, it is quite simple to create JSON or convert other existing data into JSON. Some web application frameworks, such as turbogears, automatically include support for JSON output.

In addition, commercial Web service providers also noticed JSON. Yahoo recently created many JSON-based Web Services. Yahoo's various search services, fulfillment plans, Del. icio. us, and highway transportation services also support JSON output. There is no doubt that other major Web service providers will also be added to support JSON.

Summary
JSON is a subset of JavaScript and python, making it easier to use and providing efficient data interaction for Ajax. It parses faster and is easier to use than XML. JSON is becoming the strongest voice of "Web 2.0. Every developer, whether a standard desktop application or web application, is increasingly aware of its simplicity and convenience. I hope you will have fun using JSON in buzzword-compliant, web-2.0-based, Ajax-enabled, and agile development.

About the author
Sean Kelly is a fan of Greek mythology and comedy and has noticed the potential of Ajax and JSON. His Ajax team argonauts intends to solve various problems in Web application development, Python, Ajax, Java, Web Services, and annoying XML. He has studied medicine, astronomy, and the digital media industry. He also insisted on daily yoga. He lives in an unknown place with his wife Mary and daughter Ariana.

 

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.