- 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
Receiving Multiple Data from the Server
var data = XMLHttp.responseText.split("\n");
By default, the responseText property exists only once, so the whole data returned from the server will be put into the string. However, often it is required that more than one piece of data is returned from the XMLHttpRequest call. There are several solutions for this scenario, but probably the easiest one is to return multiple data and separate the individual data using a separation character that does not occur in the data itself (for instance, a tabulator or a new line or the pipe symbol). Then it is possible to use JavaScript to access this information.
For this phrase, the following server-side text file is queried using HTTP. (In a real-world scenario, there would certainly be a dynamic script on the server side, but for demonstration purposes, the static file is just good enough.)
Multiple Data in One File (phrasebook-multiple.txt)
JavaScript Phrasebook Sams Publishing
Then, the following code accesses the individual information in the returned data; Figure 11.1 shows the result.
Working with Multiple Data from the Server (xmlhttpmultiple.html)
<script language="JavaScript" type="text/javascript" src="xmlhttp.js"></script> <script language="JavaScript" type="text/javascript"> var XMLHttp = getXMLHttp(); XMLHttp.open("GET", "phrasebook-multiple.txt"); XMLHttp.onreadystatechange = handlerFunction; XMLHttp.send(null); function handlerFunction() { if (XMLHttp.readyState == 4) { var data = XMLHttp.responseText.split("\n"); window.alert(data[0] + " " + data[1] + " by " + data[2]); } } </script>
Figure 11.1 The server sends multiple data.