I don’t know if it “works” or not, but I am concluding this because the code posted here, works (except for what’s in the for loop (stupid DOM), but that’s not the focus) ONLY after two clicks. I’m assuming this is because it is not getting the XML document till it’s created, which is at the end of the first click.
However, if I were to put XMLhttpRequest.open and XMLHttpRequest.send methods BEFORE the onreadystatechange function, the code will not execute inside the nested if statement (the one that checks readystate/status). I have tested this with alert or document.write.
Any ideas what is going wrong?
if (window.XMLHttpRequest)
{
var xmlhttp = new XMLHttpRequest();
}
function lessonList()
{
var xmldoc = xmlhttp.responseXML;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var getTitle = xmldoc.getElementsByTagName('title');
var lessonList = document.getElementById('lesson-list');
for (i = 0; i < getTitle.length; i++)
{
var lessonTitle = document.createElement('li');
lessonTitle.nodeValue = getTitle[i].childNodes[0].nodeValue;
lessonList.appendChild(lessonTitle);
}
}
};
xmlhttp.open("GET", 'file.xml', true);
xmlhttp.send(null);
}
+1 idealmachine’s answer. To clarify, there isn’t one single
Documentinstance associated with a singleXMLHttpRequest, where loading XML from the response just updates the contents of the document. It’s not like callingDocument.load().Instead, when the request is sent, the
XMLHttpRequestobject drops the oldDocumentthat was referred to by itsresponseXML, and when the response is received it creates a newDocumentinstance with the response. If you kept a reference to the old value ofresponseXMLthat’s still a validDocument, but it’s the old XML document from the previous response, not the new one.Additionally remember your
var iin the for-loop to avoid an accidental global. And setting thenodeValueis meaningless on anElementnode; you would need todocument.createTextNode(string)and append it instead.You’ll usually use a helper function to get/set the text content of an Element since traditional-DOM makes it such a pain. DOM Level 3 Core’s
element.textContentproperty is the easy way, but it doesn’t exist in IE or some older browsers.