ehfeng ehfeng - 6 months ago 20
Javascript Question

Use Javascript to retrieve HTML on same-domain

Say I have an xml document on a webserver (www.example.com/example.xml). On my main page, if I would like to retrieve that document as a string, how can I do this?

I tried xmlhttprequest - maybe I'm using it wrong? It returns it as "undefined." Help?


var xml_page = new XMLHttpRequest();
xml_page.open("GET", "http://www.samedomain.com/example.xml", true);
if (xml_page.readyState == 4 && xml_page.status == 200) {
var data = xml_page.responseText;
}
document.write(data);


Answer

Your document.write fires before the data bas been fetched, to get your code work work mostly as-is, it'd have to be a synchronous request, like this:

xml_page.open("GET", "http://www.samedomain.com/example.xml", false);
xmlhttp.send(null);

However, it's better to keep it asynchronous (which eliminates document.write...also a good thing), like this:

xml_page.open("GET", "http://www.samedomain.com/example.xml", true);
xmlhttp.onreadystatechange = function() {
  if (xml_page.readyState == 4 && xml_page.status == 200) {
    alert(xml_page.responseText);
  }
};
xmlhttp.send(null);