I have requested the data from our CGI in XML format. I do this asynchronously and have a callback function like so:
var serverData;
function serverDataCallback(event) {
if (event.target.readyState === 4) {
if(event.target.status === 200) {
var serverData = event.target.responseXML;
}
}
If I console.log the event, I get an XMLHttpRequestProgressEvent.
The target.responseXML is exactly what I want, it looks like this in the Chrome debugging console of type Document:
<Params>
<VCA>
<Ch0>
<enable>yes</enable>
</Ch0>
</VCA>
</Params>
However, I have no idea how to process this information! I have had a look at lots of tutorials and the following does not work:
serverData.getElementByTagName('Ch0')[0].getElementByTagName('enable')[0]
There is just an exception saying that getElementByTagName does not exist.
If I console.log the serverData it is reported as a Document
I’ve never done an XML HTTP Request to return XML before, so don’t really know what I’m doing! Could anyone shed some light?
If you want to use the DOM (like you are in your example), you need to walk down the element tree just as elaborately as the XML document is. You also need to spell the functions correctly; it’s called
getElementsByTagNameand notgetElementByTagNamesince there’s nothing unique about a tag name and thus the method will return an array of matching elements. A DOM solution would be something like this:There should of course be a lot of error checking here (each call to
getElementsByTagNamemay return null), but it will hopefully get you started. I would, however, encourage you to not use the DOM orXmlHttpRequestdirectly, but instead an abstraction like jQuery:As you can see, it’s much less code and you get nice translation from the XML to a jQuery object that is a lot more powerful than DOM objects.