问题描述:
问题描述:xmlhttp.readyState总是等于0,readyState状态无法改变。
有错代码:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("input[id='username']").blur(function () {
$(this).addClass("checkUsername");
xmlHTTP = new XMLHttpRequest(); //全局变量
xmlHTTP.onreadystatechange = checkUsername(); //回调函数
xmlHTTP.open("GET","checkusername"); //开启连接
xmlHTTP.send(null);
})
});
function checkUsername() {
console.log("111");
console.log(xmlHTTP.readyState);
if (xmlHTTP.readyState == 4) {
if (xmlHTTP.status == 200) {
console.log("222");
console.log(xmlHTTP.responseText);
}
}
}
</script>
有错代码运行测试如截图,很显然它的readyState=0
原因及解决方法:
原因是我的回调函数后面多加了一个括号,现做出修改如下:
xmlHTTP.onreadystatechange = checkUsername; //回调函数
后面终于得到我想要的结果了,每次readyState改变都会调用onreadystatechange函数,结果如下图: