2010-12-16 64 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