onreadystatechange function never gets called

一世执手 提交于 2020-01-06 01:59:14

问题


Ok...so my code is very simple. The only problem is that the function to be called onreadystatechange is never getting executed. I put in an alert to display the readyState and the status of xmlhttp which displayed it as 1 and 0 respectively. I cannot understand why the state is not changing. Also i do know for sure that everything else works fine. I put in alert boxes to display the username that i'm taking from the form...it displays it properly. Please help me out here....i just cannot figure this out...

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:


You need switch the calling order of xmlhttp.onreadystatechange and xmlhttp.open to make sure the onreadystatechange callback is registered before opening.

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


来源:https://stackoverflow.com/questions/15587947/onreadystatechange-function-never-gets-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!