Reputation: 14404
i created the following javascript:
<script>
function stats(cod) {
var th = document.getElementsByTagName("th");
var tds = document.getElementsByClassName("pt");
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var xmlDoc = httpRequest.responseXML.documentElement;
th[0].innerHTML = xmlDoc.getElementsByTagName('name')[0].firstChild.nodeValue;
tds[0].innerHTML = xmlDoc.getElementsByTagName('what')[0].firstChild.nodeValue;
tds[1].innerHTML = xmlDoc.getElementsByTagName('office')[0].firstChild.nodeValue;
tds[2].innerHTML = xmlDoc.getElementsByTagName('www')[0].firstChild.nodeValue;
tds[3].innerHTML = xmlDoc.getElementsByTagName('over')[0].firstChild.nodeValue;
}
}
httpRequest.open("GET","getData.php?codice=" + cod, true);
httpRequest.send(null);
}
</script>
I'm sure it is a better way to read the XML content and assign its values to the table TDs. I tried to get an array of all elements contained within xmlDoc
using xmlDoc.getElementsByTagName('response').childNodes;
but the result seems to be undefined.
EDIT:
Here is a sample of the XML:
<response>
<name>The name</name>
<what>What is</what>
<office>The office</office>
<www>The website</www>
<over>Yes</over>
</response>
Upvotes: 0
Views: 2910
Reputation: 167446
You can easily access the response
element as
var response = httpRequest.responseXML.documentElement;
I would then not try to use childNodes
as that can include text node between elements while using response.children
would give you the child elements, but only in modern browsers. In that case elements also have a textContent
property you could use in case of all those firstChild.nodeValue
accesses:
var childElements = response.children;
th[0].innerHTML = childElements[0].textContent;
tds[0].innerHTML = childElements[1].textContent;
...
On the other hand once the order of elements in your XML changes or an element is omitted you will read out the wrong data so there is some advantage in using e.g. response.getElementsByTagName('www')[0].textContent
to go by the name.
Upvotes: 1
Reputation: 943108
getElementsByTagName
returns an array-like collection of elements.
A specific element (including each member of a collection) may have childNodes
. The collection itself won't.
Upvotes: 1