我知道以前也曾提出过类似的问题,但是尽管已经阅读了足够多的内容,但我仍未能解决我的问题。
我正在创建用户名输入,并使用AJAX从服务器检索响应,具体取决于是否已使用用户名。
var timer = null;
var passed4Before = false;
var xhttp = null;
var ajaxInProgress = false;
var username = document.getElementById("username");
username.onkeyup = function(e) {
// Check if username exists in the database
function usernameExists(value) {
if (keypressed.match(/[a-z0-9-_]/gi) || e.which === 8 || e.which === 46) {
clearTimeout(timer);
ajaxInProgress = true;
timer = setTimeout(function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
document.getElementById("div").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "php.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + value);
}, 1500);
}
};
if (this.value.length >= 4) {
// Check if user has typed above 4 characters
passed4Before = true;
}
// AN ATTEMPT TO ABORT THE AJAX REQUEST WHILE IT HAS STARTED THAT HAS FAILED
// RESULT: THE AJAX DOESN'T WORK AT ALL
if (ajaxInProgress) {
xhttp.abort();
ajaxInProgress = false;
}
if (this.value.length < 4) {
if (passed4Before) {
console.log("The username cannot be less than 4 characters");
passed4Before = false;
// To stop ajax request of the previous key press (if it hasn't started yet)
clearTimeout(timer);
}
} else {
usernameExists(this.value);
}
};
我100%确定必须以某种方式使用xhttp.abort(),但我还没有发现。
我正在使用ajaxInProgress变量来确定是否有一个活动的AJAX请求,如果有,当我再次键入时,它必须停止并检查输入的新值。
当前形式的代码无法实现这一点,但是,它永远不会发出AJAX请求,或者先发送一个请求然后停止。
我希望使用没有任何第三方插件的JavaScript解决方案。任何帮助将不胜感激。
对于将来可能需要的人,这里是经过编辑的功能:
function usernameExists(value) {
if (keypressed.match(/[a-z0-9-_]/gi) || e.which === 8 || e.which === 46) {
if (xhttp) {
xhttp.abort();
}
xhttp = new XMLHttpRequest();
clearTimeout(timer);
timer = setTimeout(function() {
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 1) {
document.getElementById("loader1").innerHTML = "<img src = \"../../Content/Images/ajax-loader.gif\"/>";
}
else if (xhttp.readyState === 4 && xhttp.status === 200) {
document.getElementById("loader1").innerHTML = "<img class = \"invisible\" src = \"../../Content/Images/ajax-loader.gif\"/>";
document.getElementById("tip1").innerHTML = xhttp.responseText;
if (xhttp.responseText.indexOf("unavailable") > 0) {
username_label.style.color = "red";
}
else {
username_label.style.color = "green";
}
}
};
xhttp.open("POST", "Register.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + value);
}, 1500);
}
};
您应该保留对active的引用XMLHttpRequest
,以防万一您触发了新的引用,请使用abort
上一个引用的方法。
更具体地说,在您的代码中,xhttp
在顶部而不是setTimeout
回调内部声明var ,然后在创建新的XHR(xhttp = new XMLHttpRequest();
)之前简单地中止前一个(如果存在):
if (xhttp) {
xhttp.abort();
}
xhttp = new XMLHttpRequest();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句