XMLHttpRequest asynchronous not working, always returns status 0

帅比萌擦擦* 提交于 2019-12-18 19:11:38

问题


Here's a sample XMLHttpRequest I cobbled together from w3schools

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
  var T="nothing";

  xmlhttp=new XMLHttpRequest();
  xmlhttp.overrideMimeType('text/plain');  // don't sc
  xmlhttp.onreadystatechange=function()
  {
    alert ("rdystate: " + xmlhttp.readyState);
    alert ("status: "   + xmlhttp.status);
    alert ("Text: "     + xmlhttp.statusText);
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      T = xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);
//T = xmlhttp.responseText;
alert(T);
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">CHange Content</button>

</body>
</html>

XMLHttpRequest always returns a zero status.

Nothing shows up in Firefox's error console.

If I change the request to synchronous one by changing the line

xmlhttp.open("GET","SBL_PROBES.htm",true);

to

xmlhttp.open("GET","SBL_PROBES.htm",false);

and un-comment the line

//T = xmlhttp.responseText;

The text of the requested file is returned.

The HTM and the file reside in the same directory. If you try this you will need a file SBL_PROBES.htm there also, it's contents are irrelevant.

I'm using Firefox 3.6.22.

Could this be a cross domain problem? If so, why does it work as a synchronous request?


回答1:


You can use a function inside the if statement. This function is executed when readystate changes to 4.

var handleResponse = function (status, response) {
   alert(response)
}
var handleStateChange = function () {
   switch (xmlhttp.readyState) {
      case 0 : // UNINITIALIZED
      case 1 : // LOADING
      case 2 : // LOADED
      case 3 : // INTERACTIVE
      break;
      case 4 : // COMPLETED
      handleResponse(xmlhttp.status, xmlhttp.responseText);
      break;
      default: alert("error");
   }
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=handleStateChange;
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);

Your old code did a asynchronous call and continued just with the alert Statement. T was empty at this time.

Ok, I'll explain a little bit how this whole thing works:

First we define two callback functions, which we call later in the request, named handleResponse and handleStateChange.

Afterwards we create a Object, which represents the XMLHttpRequest

var xmlhttp=new XMLHttpRequest();

This results in an Object as follows (simplyfied):

XMLHttpRequest { status=0, readyState=0, multipart=false, onreadystatechange=handleEvent()}

With the open(...) function call you set parameters for the request:

xmlhttp.open("GET","SBL_PROBES.htm",true);

This means, do a asynchronous GET Request to fetch the Page SBL_PROBES.htm Then the send(...) function is called which fires the request itself.

We registered a callback function for the onreadystatechange, as you can imagine, this is actually an eventHandler. Each time the state changes this function is called. (It is the same as if you register a callback function to an onKeyUp Event in a form, this callback is triggered each time your key goes up :) )

The only case which is of interest for your problem is state 4. Therefor the handleRequest callback function is called only in state 4. At this time you Request has actually a result, and further a status. (Status means your webserver returned a status code 200=ok, 404=not found etc.)

That is not all the magic which is behind the ajax stuff, but should give you a simplified overview, what is actually happening behind the scenes. It is important that you test this on a webserver, do not use file:// for testing.

If you need more in detail info, just let me know.




回答2:


Status Zero happens for two reasons.

  1. You are running off the file protocol.
  2. Something is posting back the page when the Ajax request is active.

I believe you are seeing #2 here. SO you need to cancel the button click.

<button type="button" onclick="loadXMLDoc(); return false;">CHange Content</button>

In your code above that alert(T) will always say nothing when the request is asynchronous.




回答3:


Its because async returns before the request returns. Synchronous requests return after the request returns.

Try manipulating your logic in here.

xmlhttp.onreadystatechange=function()
  {
    alert ("rdystate: " + xmlhttp.readyState);
    alert ("status: "   + xmlhttp.status);
    alert ("Text: "     + xmlhttp.statusText);
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      T = xmlhttp.responseText;
      alert(T);
    }
  }



回答4:


I've battled the problem of not getting a result when using asynchronous XMLHttpRequest open statement. Since this question is the first I found when using google, here is how I solved it:

If you use a button that is inside a form, make sure it is set to type="submit" and onclick="return myFunction()". And in myFunction(), make sure you return false, not true! By returning true from the function, you reload the page and the XML object disappears. If you return false, the XML request gets the time it needs to complete and the onreadystatechange function will be run.

Source: Flask Mailing List




回答5:


I have now received the good response to this common problem. The response follow:

This is a very common problem when developing for the web. There's two ways around it.

  1. The first is to use JSONP, which our API supports when you add a query parameter ("?callback=foo"). This should get you up and running right away and is great for development, but it isn't secure for production use since users get access to your API key.
  2. The second (which is what we use on Forecast, and is the best method for production) is to set up a proxy server on your own domain which can make requests to Forecast on the user's behalf. This sidesteps the browser's same-origin policy, prevents users from accessing your API key (which can be stored server-side), and also allows you to make use of request caching, if desired. (Our favorite web server, NGINX, supports this out of the box and is really easy to configure. If you need some sample configurations, let us know!)


来源:https://stackoverflow.com/questions/7393484/xmlhttprequest-asynchronous-not-working-always-returns-status-0

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