AJAX:在readyState=1时停止运行

AJAX: stops running at readyState = 1

本文关键字:运行 1时 readyState AJAX      更新时间:2023-09-26

这是我的脚本:

var Ajax = {
    init: function(){
        try{            
            this.xmlHttp = new XMLHttpRequest();            
        }        
        catch( e ){            
            try{                
                this.xmlHttp = new ActiveXObject( "Microsoft.XMLHttp" );                
            }            
            catch( e ){                
            }            
        }        
        return this;
    },
    get: function( url , async , fn ){
        this.xmlHttp.open( "GET" , url , async );
        console.log( "1" );
        this.xmlHttp.setRequestHeader( 'Content-Type' , 'application/x-www-form-urlencoded' );
        console.log( this.xmlHttp.readyState );
        this.xmlHttp.onreadystatechange = function(){
            console.log( "3" );
            if( this.xmlHttp.readyState == 4 ){
                if( this.xmlHttp.status == 200 ){
                    try{
                        if( fn ) return fn( this.xmlHttp.responseText );
                    }
                    catch( e ){
                        alert( e );
                    }
                }
                else alert( "bad status" );
            }
            else alert( "bad state" );
        }
    }
}

还有一条线路:

Ajax.init().get( "localhost/engine.php" , true , function( txt ){alert(txt)});

现在,在控制台上,我得到了这个:

1
1

因此,当readyState为1时,我理解this.xmlHttp.onreadystatechange = function(){的运行停滞。你能告诉我这里怎么了吗?我是不是遗漏了一些更大的错误?

经过研究,xmlHttp似乎并没有真正打开url(在Chrome的控制台和Firebug中看不到请求)

您从未真正启动过请求!在get()函数的末尾添加以下内容:

this.xmlHttp.send();

希望这能帮助