onreadystatechange函数永远不会被调用

时间:2013-03-23 14:34:48

标签: javascript ajax onreadystatechange

好的......所以我的代码非常简单。唯一的问题是调用onreadystatechange的函数永远不会被执行。我输入一个警告来显示readyState和xmlhttp的状态,它分别显示为1和0。我无法理解为什么国家不会改变。此外,我确实知道其他一切正常。我放入警告框以显示我从表单中获取的用户名...它正确显示它。请帮帮我......我只是想不出来......

function checkAvailability() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp) {
        var regform = document.getElementById("regform");
        var username = regform.username.value;
        xmlhttp.open("POST", "http://localhost:8080/UsernameAvailability", true);
        xmlhttp.onreadystatechange = function() {
            alert(xyz);
        }
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send("username=" + username.value);
    }
}

1 个答案:

答案 0 :(得分:4)

您需要切换xmlhttp.onreadystatechangexmlhttp.open的通话顺序,以确保在打开前注册了onreadystatechange回调。

xmlhttp.onreadystatechange = function() {
  alert(xyz);
};
xmlhttp.open("POST", "http://localhost:8080/UsernameAvailability", true);