XmlHTTPRequest sample code does not work
I want to write a simple Javascript program that will fetch a text file and display it using alert. So, being optimistic, I went to the w3schools page that purports to offer sample programs and I tried one:
http://www.w3schools.com/dom/tryit.asp?filename=try_dom_xmlhttpr开发者_如何转开发equest_first
It doesn't work. I substituted their URL for mine. I played with their code in an attempt to get it to work. Still nothing.
I have a sneaking suspicion that my file, which is hosted on Comcast, is not being read because Comcast is blocking Javascript access to files. But I hope I am wrong. I also tried http://yahoo.com, and still I get a zero-byte response.
Here is my latest code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="myDiv" > xyz </div>
<script type="text/javascript">
<!--
var xmlHttp = null;
function writeDiv (divName, content)
{
document.getElementById(divName).innerHTML = content;
}
function Fetch()
{
var Url = "http://yahoo.com";
document.getElementById("myDiv").innerHTML = "processing...";
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open("GET", Url, true );
xmlHttp.send(null );
}
function ProcessRequest()
{
if (xmlHttp.readyState == 4) {
writeDiv ("myDiv", xmlHttp.responseText);
}
}
Fetch();
//-->
</script>
</body>
</html>
Help?
- You can't access data on other sites. The same origin policy prevents this for security reasons.
- You have commented out your JavaScript, so it won't execute (if the file is processed as XHTML instead of HTML). I wrote an article on the subject a while ago if you want more details.
- Don't trust W3S. See http://w3fools.com/
new XMLHttpRequest()
won't work on older versions of Internet Explorer (according to leeeb, support for that syntax was added in IE 7)
精彩评论