2011-02-01 24 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; 
      } 
    } 
};