Ajax|js
(translate) using JSON to accelerate Ajax
Using JSON to accelerate Ajax
by Sean Kelly
When Microsoft added an ActiveX XMLHTTP object to execute JavaScript in IE, it seemed to sow the spark of a revolution in the Web application development of Ajax. Today, Firefox, Safari, Opera, and other browsers offer xmlhttprequest that allow them to access colr.org, backpackit.com, Maps.google.com. These sites are characterized by their application performance and feel like other desktop applications, even though they run in the browser.
Inside Ajax, when a user views and interacts with a page, the page's JavaScript code requests data from the Web server ("asynchronous" in Ajax). These requests are HTTP requests, like a browser getting the page in the first place, which can include any picture, style sheet, and so on. Similarly, XMLHttpRequest objects can be used to get all kinds of data, not just XML. For example, JavaScript can use XMLHttpRequest to get a normal text file from a Web server and display its contents inside a form.
The XMLHttpRequest object analyzes the MIME type of the data returned from the Web server by looking for the Content-type header at the front of the data. For example, if the type is Text/plain, you can access the text by checking the ResponseText property of the XMLHttpRequest object. However, if the type is a Text/xml,xmlhttprequest object there is a special step: it runs an XML parse on the returned document and creates a Document Object model (DOM) tree in memory to describe the document, making the document available in the Responsexml property. You can then manipulate the object tree and access each element, attributes, and other text in the tree using JavaScript's standard Dom method.
XML is a standard method of exchanging data, but is usually not the best approach. Although XML can add structure and metadata to your data, this is a really tricky approach. XML also has a fairly complex syntax that requires a parser class to parse it. In JavaScript, XML must be parsed into a DOM tree before it can be used. And once the DOM tree is built, you also have to create the appropriate JavaScript objects or other methods to use the XML data in the client application.
Fortunately, there is a better way.
Using JSON
JSON, also known as JavaScript Object notation, is a lightweight syntax for describing data. JSON is elegant because it is a subset of the JavaScript language. Next you'll see why it's so important. First, compare the JSON and XML syntax.
Both JSON and XML use structured methods to describe the data. For example, an address book application can provide a Web service to generate an address Card in XML format:
Sean Kelly.
SK Consulting
Kelly-at-seankelly-dot-biz
kelly-AT-seankelly-DOT-tv
+1 214 555 1212
+1 214 555 1213
+1 214 555 1214
1234 Main St
Springfield, TX 78080-1216
5678 Main St
Springfield, TX 78080-1316
http://seankelly-DOT-biz/
http://seankelly-DOT-tv/
Using JSON, the form is as follows:
{
"FullName": "Sean Kelly",
"org": "SK Consulting",
"Emailaddrs": [
{' type ': ' Work ', ' value ': ' Kelly-at-seankelly.biz '},
{' type ': ' Home ', ' pref ': 1, ' value ': ' Kelly-at-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 that are similar to XML. JSON is also text-based, and so is XML. Both use Unicode. JSON and XML are easy to read. Subjectively, JSON is clearer and less redundant. The JSON web site is a strict description of the JSON syntax, and this is the way it is now. It's really a simple little language! XML is really good for tagging documents, but JSON is the ideal format for data interaction. Each JSON document describes an object that contains: nested objects, arrays, strings, numbers, Boolean values, or null values.
In these address Card example codes, the JSON version is lighter, takes up only 682 bytes of space, and the XML version requires 744 bytes of space. Although this is not a considerable savings. And the real benefit comes from the parsing process.
XML vs. JSON: status loss
By using the XMLHttpRequest object, you can get XML and JSON files from your AJAX-based applications. Typically, 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, you provide a processor function (MyHandler function) that is called multiple times to provide you with an opportunity to terminate the transaction prematurely and update the progress bar. Typically, it works only after the Web request is completed: You can then use the returned data.
To handle an XML version of the Address card data, the MyHandler code is as follows:
function MyHandler () {
if (req.readystate = = 4/*complete*/) {
Update address field in a form with the address
var Addrfield = document.getElementById (' addr ';
var root = Req.responsexml;
var Addrselem = root.getelementsbytagname (' addresses ' [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 the Responsexml is available. By using the Responsexml property, you can call the getElementsByTagName method to find the address part of the document, and you can also use the first to find it. You can then call getElementsByTagName again to find the first address element in the address section. This gets the first dom child node of the document, which is a text node and gets the value of the node, which is the street address you want. Finally, you can display the results in the form field.
It's really not a simple job, now, use JSON and try again:
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 JavaScript's own compiler to parse it by invoking the Eval function. Parsing JSON requires only one line! In addition, manipulating objects in JSON is like manipulating other JavaScript objects. This is obviously easier to manipulate than through a 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 a home address object
Card.fullname is the name of the card, "Sean Kelly."
If you look more closely, you may find that there is at least one element in the XML format for Chinese files, card. This doesn't exist in JSON, why? Presumably, if you're developing JavaScript to access Web services, you already know what you want. However, you can use this in JSON:
{"card": {"FullName": ...}}
With this technique, your JSON file is always started with an object with a single named attribute that identifies the object's kind.
is JSON fast and reliable?
JSON provides lightweight small documents, and JSON is easier to use in JavaScript. XMLHttpRequest automatically parses XML documents for you, and you have to parse JSON files manually, but is parsing json slower than parsing XML? The author uses XMLHttpRequest to parse XML and parse JSON with thousands of repeated tests, and the result is that parsing json is 10 times times faster than XML! When you look at Ajax as a desktop application, speed is the most important factor, and obviously, JSON is better.
Of course, you can't always control the server side to generate data for AJAX programs. You can also use a third-party server instead of a server to provide XML-formatted output. And if the server just provides JSON, can you be sure you really want to use it?
It is noteworthy in the code that you pass the response text directly to the eval. If you control the server, you can do so. If not, a malicious server can enable your browser to perform dangerous operations. In this case, you'd better use code written in JavaScript to parse JSON. Luckily, it's already there.
When it comes to parsing, Python enthusiasts may notice that JSON is not just a subset of JavaScript, it's a subset of Python. You can execute JSON directly in Python, or use secure JSON resolution instead. The json.org Web site lists many common JSON parsers.
Server-side JSON
Up until now, you may have focused on using JSON in an AJAX-based Web application running in a client's browser. Naturally, first of all, JSON-formatted data must be generated on the server side. Fortunately, it is fairly straightforward 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, the business Web service provider has noted the JSON. Yahoo has recently created a number of JSON based Web services. Many of Yahoo's search services, fulfillment programs, del.icio.us, and highway Traffic services also support JSON output. There is no doubt that other major Web service providers will also be added to the support of JSON.
Summarize
The smart thing about JSON is that it's a subset of JavaScript and python that makes it easier to use and provides efficient data interaction for Ajax. It is faster to parse and easier to use than XML. JSON is becoming the strongest sound of Web 2.0 now. Every developer, whether a standard desktop application or a Web application, is increasingly aware of its simplicity and convenience. I hope you can appreciate the fun of applying JSON to Buzzword-compliant, web-2.0-based, ajax-enabled, and agile development.
About the author
Sean Kelly is a Greek mythology and comedy enthusiast, noting the potential role of Ajax and JSON. His AJAX team Argonauts to address various issues in Web application development, Python,ajax,java,web services, and annoying XML. He has studied medicine, astronomy and the digital media industry, and insists on doing yoga every day. He and his wife Mary and daughter Ariana live in an unknown place.
<