Javascript AJAX:在readyState=1时停止运行
这是我的剧本:Javascript AJAX:在readyState=1时停止运行,javascript,ajax,Javascript,Ajax,这是我的剧本: var Ajax = { init: function(){ try{ this.xmlHttp = new XMLHttpRequest(); } catch( e ){ try{ this.xmlHttp = new Ac
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(){
上运行的stuck。您能告诉我,这里出了什么问题吗?我是否遗漏了一些更大的错误
仔细研究后,似乎xmlHttp并没有真正打开url(Chrome的控制台和Firebug中没有看到任何请求).您从未真正启动过请求!在get()函数末尾添加以下内容:
this.xmlHttp.send();
希望这有帮助:@Sudhir不是真的。我需要它交叉排列,不能依赖于
。onload
试着理解它可能会让你清楚你的代码有什么问题。你也可以尝试在mozilla中使用firebug调试你的javascript。我已经使用AJAX很长时间了,但不是我上面写的方式。我知道怎么做它可以工作(或者,我想,我想我知道)。问题在于这个脚本中,我只是错过了它……您需要在回调中输出readyState
的值,以便对其进行更改,而不是在您发出请求后直接输出。