- Initializing an AJAX Application
- Sending a GET Request
- Sending a POST Request
- Sending a Synchronous Request
- Receiving Multiple Data from the Server
- Aborting an HTTP Request
- Retrieving HTTP Headers
- Receiving XML from the Server
- Using JSON for Data (De)Serialization
- Creating a Waiting Screen
- Solving the Bookmark Problem
- Solving the Back Button Problem
- Using XSLT
- Using an XML Library
- Using the Yahoo! Web Service
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 object—a 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="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>