这个Ajax代码有问题,每次访问“readyState”时都返回0。不知道问题的根源是什么,任何帮助都是非常感谢的:
var xhr = null;
function performAjax(inputUrl){
// instantiate XMLHttpRequest object
try{
xhr = new XMLHttpRequest();
alert("XMLHttpRequest");
}
catch(e){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// handle old browsers
if( xhr == null ) {
alert("Ajax not supported by your browser");
return;
}
// get the URL
var url = inputUrl;
alert(inputUrl);
// get Ajax answer
xhr.onreadystatechange = handler();
//alert(xhr.readyState);
xhr.open("POST", url, true);
xhr.send(null);
}
function handler() {
alert("Handler: " + xhr.readyState + " Status: " + xhr.status);
// handle only loaded requests
if(xhr.readyState == 4) { // state 4: that data has been received
alert("here");
if(xhr.status == 200) {
alert(xhr.reponseText);
}
else alert("Error with Ajax");
}
}发布于 2014-02-18 21:13:29
您不正确地分配处理程序函数:
xhr.onreadystatechange = handler; // <--- THERE SHOULD BE NO PARENTHESES当您包含括号时,您要求调用该函数。没有它们,你仅仅是指函数,这就是你想要的。
https://stackoverflow.com/questions/21865375
复制相似问题