Ajax readyState总是返回0

Seb*_*ian 2 javascript ajax

我遇到了这个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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

您错误地分配了处理函数:

xhr.onreadystatechange = handler; // <--- THERE SHOULD BE NO PARENTHESES
Run Code Online (Sandbox Code Playgroud)

当您包括括号时,您要求调用该函数.没有它们,你只是指功能,这就是你想要的.