Home > Articles > Open Source > Ajax & JavaScript

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

This chapter is from the book

Receiving XML from the Server

var xml = XMLHttp.responseXML;

The responseText property works well for a limited amount of unstructured data. However, a more elegant approach for using complex, structured data within an AJAX application promises to be the responseXML property. When accessing this property, you get the response of the HTTP request as a JavaScript XML DOM object—of course, only if the server returns valid XML; otherwise, you get null.

Accessing the details of the XML object is quite similar to accessing DOM elements from JavaScript. For this phrase, the following sample XML file will be used:

Sample XML Data (phrasebook.xml)

<books>
  <book pubdate="2006">
    <title>JavaScript Phrasebook</title>
    <publisher>Sams Publishing</publisher>
  <book>
</books>

For the web browsers to read in this XML (Internet Explorer especially is very strict in that regard), the correct MIME type must be sent to the client: text/xml. If you are using Apache, the following configuration in mime.types should do the trick, but is already there by default:

text/xml

On Internet Information Services, you can configure the MIME types in the administration console (Start, Run, inetmgr). Alternatively, let a server-side script serve the file with the correct MIME type; generally this is a must if you are using server-side technology to generate the XML:

Setting the Correct Response MIME Type (phrasebook.xml.php)

<?php
  header('Content-type: text/xml');
  readfile('phrasebook.xml');
?>

Then, the following code accesses the information in the XML file, using the DOM structure and methods like getElementsByTagName() and getAttribute(). Figure 11.2 shows the result.

Extracting Information from the HTTP Response (xmlhttpxml.html)

<script language="JavaScript"
  type="text/javascript" src="xmlhttp.js"></script>
<script language="JavaScript"
  type="text/javascript">
var XMLHttp = getXMLHttp();
XMLHttp.open("GET", "phrasebook.xml");
XMLHttp.onreadystatechange = handlerFunction;
XMLHttp.send(null);

function handlerFunction() {
  if (XMLHttp.readyState == 4) {
    var xml = XMLHttp.responseXML;
    var book = xml.getElementsByTagName("book")[0];
    var pubdate = book.getAttribute("pubdate");
    var title, publisher;
    for (var i=0; i<book.childNodes.length; i++) {
      if (book.childNodes[i].nodeName == "title") {
        title = book.childNodes[i].firstChild.nodeValue;
      } else if (book.childNodes[i].nodeName == "publisher") {
        publisher = book.childNodes[i].firstChild.nodeValue;
      }
    }
    window.alert(title + " by " + publisher +
                 " (" + pubdate + ")");
  }
}
</script>
Figure 11.2

Figure 11.2 The data from the XML file.

  • + Share This
  • 🔖 Save To Your Account