2011-02-01 42 views
4

嗨即时通讯目前正在一个xmhhttp请求延迟功能,但该网站需要一些时间来加载,所以我只得到的readyState = 3和状态= 200。所以我需要的东西,等待,直到readyState的= 4,但是我想限制这个函数,以便它在readystate = 4时只检查一次,否则什么也不做。需要Javascript

这样的延迟功能怎么样?

if (xmlhttp.readyState==4 && xmlhttp.status==200)//Add the delay here so that the else doesn't occur 
    { 
    var txt=xmlhttp.responseText; 
    ..... 
    else { 

    document.write("status: " + xmlhttp.readyState + " " + xmlhttp.status); 
    } 

回答

0

我们可以编写一个函数来检查您的XMLHTTP对象的状态:

var checkState = function(xmlhttp, callback) { 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
    callback(whatever, arguments, that, you, want, to, send); 
    } else { 
    // Check back again 1 sec later 
    setTimeout(checkState, 1000); 
    } 
}; 

然后你可以使用它像这样:虽然

checkState(xmlhttp, function(whatever, arguments, you, need) { 
    // the code here will be run when the readyState is 4 and the status is 200 
}); 

两件事情:

  • checkState函数将返回无论o f readyState,所以确保你只做在回调中依赖它的事情,而不是在之后。
  • 如果readyState的和状态永远不会得到你想要的值,你的运气了(但你可以扩展函数接受将要处理超时情况下,第二个回调)。
2

,如果我理解正确,一个setInterval可能做的伎俩:

var seconds = 0; 
var interval = setInterval(function() { 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     // Stop checking 
     clearInterval(interval); 
     // Ready 
     var txt = xmlhttp.responseText; 

    } else if (++seconds > 10) { // Do we give up? 
     clearInterval(interval); 
     // Give up 

    } 
}, 1000); // Checks once every second 
-2

可能使用类似

编辑:使用的onreadystatechange:

Connection.onreadystatechange = function() 
{ 
    if (Connection.readyState != 4) 
    { 
     return; 
    } 
    else 
    { 
     // do your thing 
    } 
}; 
+0

这不是一个答案;你几乎复制了这个问题本身。他正在问如何做“等一下” - 部分:) – Jakob 2011-02-01 15:37:28

+0

但他要求“等待”代码 – Magnus 2011-02-01 15:38:23

4

你为什么会发明轮子?

你应该只传递一个句柄到XHRsonreadystatechange回调。

xmlhttp.onreadystatechange = function() { 
    switch(xmlhttp.readyState) { 
      case 4: { 
       if (xmlhttp.status === 200) { 
        var txt = xmlhttp.responseText; // or do something else here 
       } 
       break; 
      } 
      case 3: { 
       // go interactive ! 
       break; 
      } 
    } 
};