2014-02-18 116 views
2

我遇到了这个Ajax代码的问题,每次访问'readyState'时返回0。不知道是什么问题的来源还没有,任何帮助,将不胜感激: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"); 
    } 
} 

回答

5

你错误地分配处理函数:

xhr.onreadystatechange = handler; // <--- THERE SHOULD BE NO PARENTHESES 

当你包括括号,你问的功能是。没有它们,你只是指这个功能,而这正是你想要的。

+0

:)知道了!非常感谢! – Sebastian

+1

@塞巴斯蒂安no no - 它不应该**有括号; **括号是问题。** – Pointy