2010-12-16 83 views
1

我正在開發使用Ajax調用,並且在調試時發現Ajax發送的請求/響應比我實際想象的要多得多。Ajax調用就緒狀態流混淆

很久以前,我得到了很好的文件描述幕後發生了什麼,但我失去了它。

當今網絡上的Ajax教程只講解如何編碼,而那些IF語句只檢查readystate == 4status == 200,這對於像我這樣的人沒有提供很好的解釋。

我用下面的代碼測試了流程,輸出結果我覺得很奇怪。我的困惑是爲什麼準備好的狀態顯示兩次?根據定義,就緒4意味着完成所以應該沒有理由完成兩次?

輸出

START 
ready 1    //loading 
START 
ready 2    //loaded 
ready 2 status=200  //loaded 
START 
ready 3    //interactive 
ready 3 status=200  //interactive 
START 
ready 4    //complete 
START 
ready 4    //complete ... again??? 

測試代碼片段

xmlHttp.onreadystatechange = function() { 

       alert("START"); 

       if(xmlHttp.readyState == 0) { 
        alert('ready 0'); 
        alert('ready 0 status=' + xmlHttp.status); 
       } 

       if(xmlHttp.readyState == 1) { 
        alert('ready 1'); 
        alert('ready 1 status=' + xmlHttp.status); 
       } 

       if(xmlHttp.readyState == 2) { 
        alert('ready 2'); 
        alert('ready 2 status=' + xmlHttp.status); 
       } 

       if(xmlHttp.readyState == 3) { 
        alert('ready 3'); 
        alert('ready 3 status=' + xmlHttp.status); 
       } 

       if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { 
        alert('ready 4'); 
       } 
    }     

回答

4

可以在quirksmode約的方式不同瀏覽器的行爲與AJAX調用和readyState的讀取。

我發現this鏈接聲稱使用Abort命令將發出readystate 4(還沒有測試過) - 你使用的是Abort

+0

感謝您的提示,不,我不認爲我使用中止。儘管我必須搜索更多關於Ajax行爲的信息 – 2010-12-18 00:38:25