Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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

Figure 11.1 The server sends multiple data.

  • + Share This
  • 🔖 Save To Your Account