XMLHttpRequest异步不起作用,总是返回状态0 [英] XMLHttpRequest asynchronous not working, always returns status 0

查看:206
本文介绍了XMLHttpRequest异步不起作用,总是返回状态0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我从w3schools拼凑而成的XMLHttpRequest示例

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

xmlhttp = new XMLHttpRequest();
xmlhttp.overrideMimeType('text / plain'); //不要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>使用XMLHttpRequest对象< / h2>
< div id =myDiv>< / div>
< button type =buttononclick =loadXMLDoc()> CHange Content< / button>

< / body>
< / html>

XMLHttpRequest始终返回零状态。



Firefox的错误控制台中没有显示任何内容。



如果我通过更改行将请求更改为同步请求

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

  xmlhttp.open( GET, SBL_PROBES.htm,假); 

并取消评论该行

  // T = xmlhttp.responseText; 

返回所请求文件的文本。



HTM和文件位于同一目录中。如果你试试这个,你还需要一个文件SBL_PROBES.htm,它的内容是无关紧要的。



我正在使用Firefox 3.6.22。



这可能是跨域问题吗?如果是这样,为什么它作为同步请求工作?

解决方案

您可以在if语句中使用函数。当readystate更改为4时执行此函数。

  var handleResponse = function(status,response){
alert(响应)
}
var handleStateChange = function(){
switch(xmlhttp.readyState){
case 0:// UNINITIALIZED
case 1:// LOADING
案例2://加载
案例3://互动
休息;
case 4:// COMPLETED
handleResponse(xmlhttp.status,xmlhttp.responseText);
休息;
default:alert(error);
}
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = handleStateChange;
xmlhttp.open(GET,SBL_PROBES.htm,true);
xmlhttp.send(null);

您的旧代码执行了异步调用,并继续使用alert语句。 T此时空了。



好的,我会解释一下这一切是如何运作的:



<首先我们定义两个回调函数,我们稍后在请求中调用,名为handleResponse和handleStateChange。



然后我们创建一个Object,它代表XMLHttpRequest

  var xmlhttp = new XMLHttpRequest(); 

这导致一个Object如下(简称):

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

通过open(...)函数调用,您可以为请求设置参数:

  xmlhttp.open( GET, SBL_PROBES.htm,TRUE); 

这意味着,执行异步GET请求以获取页面SBL_PROBES.htm
然后调用send(...)函数来激活请求本身。



我们为onreadystatechange注册了一个回调函数,你可以想象,这实际上是一个eventHandler。每次状态改变时,都会调用此函数。 (就像你将一个回调函数注册到表单中的onKeyUp事件一样,每次你的密钥上升时都会触发这个回调:))



唯一对你的问题感兴趣的情况是状态4.因此,只在状态4中调用handleRequest回调函数。此时你的Request实际上有一个结果,并且还有一个状态。 (状态表示您的网络服务器返回状态代码200 = ok,404 =未找到等。)



这不是ajax背后的所有魔法,但应该给你一个简化的概述,幕后实际发生的事情。
在网络服务器上进行测试非常重要,不要使用file://进行测试。



如果您需要更多详细信息,请让我们我知道。


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?

解决方案

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.

这篇关于XMLHttpRequest异步不起作用,总是返回状态0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆