javascript - AJAX:在 readyState = 1 时停止运行

标签 javascript ajax

这是我的脚本:

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();

希望对你有帮助

关于javascript - AJAX:在 readyState = 1 时停止运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9498714/

相关文章:

Javascript 正则表达式从错误的起点匹配

asp.net - 每当触发客户端 ASP.NET 验证程序时运行自定义 Javascript?

javascript - Ajax无限滚动图库多次添加相同的图像

jquery - 获取 JSON 对象的某个值的索引

javascript - ajax脚本不更新信息

javascript - 如何使服务器响应无效

javascript - 在满足条件时为文本着色

javascript - Canvas - lineTo (x, y) 不生成超过一行

javascript - 为什么要使用 HTML 5 Canvas 标签?

javascript - 为什么ajax调用在IE7上不起作用