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="/books/3/490/1/html/2/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.





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