简体   繁体   中英

Stuck trying to parse XML using AJAX and Javascript with XMLHttpRequest

Re-edit of the InnerHtml to show how many Div's will be included in the finished code. Also a re-edit of the start function which now does not work and I'm not sure at what point I broke it.

 var fname = name; function load() { var x = new XMLHttpRequest(); x.open ("GET", "file1.xml",true); x.onreadystatechange = handleServerInput; x.send(); xml =x.responseXML; fname = xml.getElementsByTagName("name")[0]; name = fname.childNodes[0].data; function handleServerInput() { if (x.readyState == 4 && x.status == 200) { function DisplayDiv() { var html = ""; html+= " <div id = \\"displayOuter\\">"; html+= " <div id = \\"displayInner\\">"; html+= " <p id = \\"fname\\">"; html+= " </p>"; html+= " </div>"; html+= " <div id = \\"displayInner2\\">"; html+= " </div>"; html+= " <div id = \\"displayInner3\\">"; html+= " </div>"; html+= " </div>"; return html; } function start() { document.body.innerHTML+=DisplayDiv(); var displayOuterDiv = document.getElementById("displayOuter"); displayOuterDiv.style.display= "block"; var innerdiv = document.getElementById('displayInner'); innerdiv.innerHTML = fname; } // alert ( this.responseText ); } } } window.onload = load; 

So I put the DisplayDiv function inside my handleServerInput function and that does imput the data to the HTML Div but only when it is set to false which I don't want. Can someone explain to me why this is? Here is an update of the code.

 var fname = name; function load() { var x = new XMLHttpRequest(); x.open ("GET", "file1.xml",false); x.onreadystatechange = handleServerInput; x.send(); function handleServerInput() { if (x.readyState == 4 && x.status == 200) { document.body.innerHTML+=DisplayDiv(); div = document.getElementById('displayInner'); div.innerHTML = fname; } function DisplayDiv() { var html = ""; html+= " <div id = \\"displayInner\\">"; html+= " <p id = \\"fname\\">"; html+= " </p>"; html+= " </div>"; return html; } } xml =x.responseXML; fname = xml.getElementsByTagName("name")[0]; name = fname.childNodes[0].data; } 

Try assigning fname before you use it. I assume you only want to use x.responseXML on a 200 response, so you should move

xml =x.responseXML;
fname = xml.getElementsByTagName("name")[0];
name = fname.childNodes[0].data; 

into your if statement, somewhere before div.innerHTML = fname; happens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM