Javascript 关闭活动ajax请求(设置超时)
当我点击复选框时,我试图停止一个活动的ajax请求。我激活了一个每秒调用一个url的ajax,但是当我取消选中复选框时,我正试图关闭ajax请求。我尝试使用listener.abort();它不起作用,我还添加了xhr.abort(),但什么也没发生。 有什么建议吗Javascript 关闭活动ajax请求(设置超时),javascript,ajax,Javascript,Ajax,当我点击复选框时,我试图停止一个活动的ajax请求。我激活了一个每秒调用一个url的ajax,但是当我取消选中复选框时,我正试图关闭ajax请求。我尝试使用listener.abort();它不起作用,我还添加了xhr.abort(),但什么也没发生。 有什么建议吗 function listener() { $.get('http://localhost:3000/get-value', function (dataf) { if (dataf.result !
function listener() {
$.get('http://localhost:3000/get-value', function (dataf) {
if (dataf.result != "") {
$.ajax({
url: "http://localhost:8000/login",
data: { pId: dataf.result },
type: "POST",
success: function (result) {
if (result.name != "") {
$.get('http://localhost:3000/close-conn');
window.location.href = result.url;
}
}
});
}
setTimeout(listener, 1000);
});
}
function GetCheckStatus() {
var flag = chkAuto.GetValue();
if (flag) {
$.ajax({
url: "http://localhost:3000/open-conn",
type: "GET",
});
listener();
} else {
$.ajax({
url: "http://localhost:3000/close-conn",
type: "GET",
});
// Doesnt work
listener.abort();
}
}
您正在对函数调用.abort()方法,而不是实际的请求对象。试试这样吧
为$.get请求和setTimeout定义变量,然后根据需要中止/清除它们
var xhr, timeout;
function listener() {
xhr = $.get('http://localhost:3000/get-value', function (dataf) {
if (dataf.result != "") {
$.ajax({
url: "http://localhost:8000/login",
data: { pId: dataf.result },
type: "POST",
success: function (result) {
if (result.name != "") {
$.get('http://localhost:3000/close-conn');
window.location.href = result.url;
}
}
});
}
timeout = setTimeout(listener, 1000);
});
}
function GetCheckStatus() {
var flag = chkAuto.GetValue();
if (flag) {
$.ajax({
url: "http://localhost:3000/open-conn",
type: "GET",
});
listener();
} else {
$.ajax({
url: "http://localhost:3000/close-conn",
type: "GET",
});
//Cancel the current request and prevent the next one from being triggered
xhr.abort();
clearTimeout(timeout);
}
}
尝试
event.stopImmediatePropagation()代码>函数没有中止方法。您必须存储jqXHR以中止它,然后清除超时。@KevinB我尝试过,但没有work@UsmanRana不我认为你试错了,