Parsing responseXML

Listing 10.3 gives an example of how we can use getElementsByTagName(), alongside some other methods discussed in Lesson 6, to return the text of our greeting in an alert dialog.

Listing 10.3. Parsing responseXML using getElementsByTagName()

 

 

function responseAjax() {
    // we are only interested in readyState
    // of 4, i.e. "completed"
    if(myRequest.readyState == 4) {
        // if server HTTP response is "OK"
        if(myRequest.status == 200) {
            var greetNode = http.responseXML.getElementsByTagName("greeting")[0];
            var greetText = greetNode.childNodes[0].nodeValue;
            alert("Greeting text: " + greetText);
        } else {
            // issue an error message for
            // any other HTTP response
            alert("An error has occurred: " + myRequest.statusText);
        }
    }
}

 

After the usual checks on the values of the readyState and status properties, the code locates the required element from responseXML using the getElementsByTagName() method and then uses childNodes[0].nodeValue to extract the text content from this element, finally displaying the returned text in a JavaScript alert dialog.

Figure 10.2 shows the alert dialog, showing the text string recovered from the <greeting> element of the XML document.

Figure 10.2. Displaying the returned greeting.