Using JSON for Data (De)Serialization


var json = XMLHttp.responseText; var book = eval("(" + json + ")");; 

JSON is becoming more and more the de facto standard data exchange format for AJAX applications. Many AJAX frameworks support JSON, many Web Services provide a JSON interface, and PHP 6 will most probably feature JSON support at the core of the language.

Using JSON within JavaScript is quite simple, as well. The preceding code evaluates JSON and converts it into a JavaScript objecta simple eval() function call does the trick.

The JSON notation from the previous sidebar, "Understanding JSON," is stored in a file called phrasebook.json; then, the following code reads in this file using XMLHttpRequest and then outputs some data from it:

Using JSON for Data Deserialization (xmlhttpjson.html)

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/xmlhttp.js"></script> <script language="JavaScript"   type="text/javascript"> var XMLHttp = getXMLHttp(); XMLHttp.open("GET", "phrasebook.json"); XMLHttp.onreadystatechange = handlerFunction; XMLHttp.send(null); function handlerFunction() {   if (XMLHttp.readyState == 4) {     var json = XMLHttp.responseText;     var book = eval("(" + json + ")");     var pubdate = book.pubdate;     var title = book.title;     var publisher = book.publisher;     window.alert(title + " by " + publisher +                  " (" + pubdate + ")");   } } </script> 

Warning

Using eval() is general ly a bad idea, since you introduce a serious security vulnerability if the JSON comes from a nontrustworthy source. Due to the same-domain restriction of XMLHttpRequest, the JSON code can usually be trusted, but if you want to feel safer, download the JSON library json.js from http://www.json.org/js.html. Then, the following code replaces the eval() call:

var book = json.parseJSON(); 






JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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