Section 3.3. JSON


3.3. JSON

A third major technology often used for Ajax applications is JavaScript Object Notation (JSON, http://www.json.org). With JSON, JavaScript objects or data can be persisted (serialized) in a short and easily understandable way, without requiring a lot of JavaScript code to either write or read the data. JSON makes use of an often-overlooked feature of JavaScript, or to be exact of the ECMAScript language specification, also known as ECMA-262.

JSON is used internally by current versions of Atlas and generally can be used to exchange complex data with a server. This allows JavaScript to understand it, also the sometimes cumbersome XML parsing with JavaScript can be avoided. The following code uses JSON to define a book object.

 {"book": {   "title": "Programming Atlas",   "author": "Christian Wenz",   "chapters": {     "chapter": [       {"number": "1", "title": "Introduction"},       {"number": "2", "title": "JavaScript"},       {"number": "3", "title": "Ajax"}     ]   } }} 

This is the same data that you saw defined using XML in Chapter 2. The object with the book property contains title, author, and chapters properties. The chapters property contains several chapter subelements, each with a number and a title property. This can be best visualized when looking at it as XML data. You will remember it as the exact same XML that was used in the previous section, "The XMLDocument Object," as shown in this code:

 <book title="Programming Atlas" author="Christian Wenz">   <chapters>     <chapter number="1" title="Introduction" />     <chapter number="2" title="JavaScript" />     <chapter number="3" title="Ajax" />   </chapters> </book> 

The main benefit of JSON is that JavaScript can evaluate the JSON notation without your having to write any code to parse it, as demonstrated in Example 3-3.

Example 3-3. Using JSON to easily create objects

 json.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JSON</title> </head> <body>   <script language="JavaScript" type="text/javascript">     var json = '{"book": { "title": "Programming Atlas", "author": "Christian Wenz", "chapters": {"chapter": [ {"number": "1", "title": "Introduction"}, {"number": "2", "title": "JavaScript"}, {"number": "3", "title": "Ajax"} ]} }}'; eval("var obj = " + json + ";");     for (var i=0; i < obj.book.chapters.chapter.length; i++) {       document.write(         "<p>" +         obj.book.chapters.chapter[i].number +         ": " +         obj.book.chapters.chapter[i].title +         "</p>"       );     }   </script> </body> </html> 

Figure 3-7 shows the result of running this script.

Figure 3-7. The result of evaluating the JSON notation


As you can see in Figure 3-7, the data from the JSON notationthe names of the three chaptersis printed out in the browser. The curly braces that appear in Example 3-3 are used to specify object properties, and square brackets are used for to define array lists. However you will also note something that looks very dangerous from a security point of view. The following line of code evaluates the JSON code at runtime:

 eval("var obj = " + json + ";"); 

Using (and Avoiding) Client-Side Caching

Browsers love to cachethis may make pages load faster. Webmasters love caching, since it can take load off a server. Developers sometimes hate cachingif an outdated version of the page is delivered, it can make debugging very frustrating. In the Ajax world, this is a very common problem. There are two easy solutions to the caching problem. One solution is to append a fake GET parameter to the URL used for the XMLHttpRequest object, which does not affect the results, yet avoids any caching because it changes the URL with each request. The following snippet shows one way to do this:

 XMLHTTP.open("GET", "xmldocument.aspx?sendData=ok&token="   + Math.random()); 

The snippet appends something like &token=0.19964476288175226 to the URL, making it unique. Alternatively, you can set an additional request header for the HTTP request, If-Modified-Since, to a date in the past, and the browser will fetch the new version each time. The following snippet illustrates this technique:

 XML.setRequestHeader(   "If-Modified-Since",   "Tuesday, 1 Jan 1980 12:00:00 GMT"); 

During development, use one of these techniques to facilitate debugging. On production systems, however, the built-in browser caching mechanism may increase the performance of your application (if it does not generate side effects with your application), and server-side caching can be even more effective. It always depends on the specific scenario in which you want to implement caching.


This line of code uses the built-in eval() JavaScript function, which dynamically evaluates code at runtime. Some programmers consider runtime evaluation bad style, but there is an even worse problem here, namely, eval() implicitly trusts the code it is running. In the example, the JSON notation is part of the script, so you can trust it. In Ajax applications, usually the JSON data comes from the same server as the client page. The trust implicit in the eval() function may be misplaced, especially when you do not control the page the JSON object comes from or when the machine that the script runs on has been misconfigured (for instance, by spyware that redirects requests from one server to another). Therefore, be careful when using eval(); only use it on code you can really trust.




Programming Atlas
Programming Atlas
ISBN: 0596526725
EAN: 2147483647
Year: 2006
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net