ajax status = 0

荒凉一梦 提交于 2020-01-03 03:13:07

问题


i'm trying to get information from a remote server on my local machine. readyState has no problem, i.e. ==4. however, status is always 0(instead of 200) when I hit the button, it returns nothing.

here is the code,:

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET",'http://www.spartanbook.com/textbooks_xml.asp?control=campus&campus=45&term=80',true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

It's basically from w3shcools. simply replaced the url. the url I'm using is working when I paste it into address bar of my browser.

Any idea? Thanks!!


回答1:


Check that you are not making a cross domain request.

If for example you are not serving this page from http://www.spartanbook.com then the expected result would be access denied, which oddly enough gives a readyState of 4, but a status of 0.

If you need to make a cross domain request, then you need to use a proxy.




回答2:


This error code indicates that the response was empty. Seems like a firewall issue




回答3:


Like Gavin says, it seems your problem is that you're making a cross domain request, which is blocked by most browsers due to security reasons: http://en.wikipedia.org/wiki/Same_origin_policy

I suggest you move the code from your local computer to a place which satisfies the "Same Origin Policy", in your case that is somewhere on www.spartanbook.com.

However, there is a workaround for the problem, and that is to use JSONP. That will allow you to fetch JSON data from a program on another domain.



来源:https://stackoverflow.com/questions/6270553/ajax-status-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!