Search code examples
javascriptxmlhttprequest

Javascript: XMLHttpRequst: How to make it work


Given below is the simplest script I put together to test XMLHttpRequest. But, no matter what I do, I don't seem to be able get it working. It ALWAYS results in error after headers are received. One of the possibility is that it's because of proxy. If it is how can I know that's the cause? Please note the code for XMLHttpRequest is taken from guide at https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/JavaScript">

function loadXMLDoc()
{

var oXHR = new XMLHttpRequest();

oXHR.onreadystatechange = function (oEvent) {
  if (oXHR.readyState === 4) {
    if (oXHR.status === 200) {
      document.getElementById("xml_req_output").innerHTML += oXHR.responseText + "\n";
    } else {
      document.getElementById("xml_req_output").innerHTML += "Error:" + oXHR.statusText  + "\n";
    }
  }
}

if ( typeof oXHR.overrideMimeType != 'undefined') {
   oXHR.overrideMimeType('text/xml');
}

var urltoget = document.getElementById("txturl").value;

document.getElementById("xml_req_output").innerHTML += urltoget + "\n";

oXHR.open("GET", urltoget, true);
oXHR.send(null);

}

</script>
</head>
<body>
<input type="text" name="txturl" id="txturl" size="200" value="http://www.mozilla.org"/>
</br>
<input type="button" onclick="loadXMLDoc()" value="Get XML"/>
</br>
<textarea cols="100" rows="50" height="400px" id="xml_req_output" >
</textarea>
</body>
</html>

Solution

  • You cannot load documents by XMLHttpRequest from diffent domains. See also the same origin policy.