[英]how to stop ajax request?
我有多個ajax請求,當其中之一無法獲取我想要的數據時,我會重新發送它,直到它可以獲取數據為止。 問題是我獲取數據后無法停止它。 在ajax中有一個休息或等同的東西嗎? 我嘗試了clearinterval,但是它不起作用,這是我的功能:
function ajaxGetServerDatabase(Div,val,interval){
console.log(val);
dbs[val]=new Array();
$('#bck_action').val('get_DB');
$('#server_ip').val(val);
post_data = $('#'+Div+' *').serialize();
$.ajax({
type: "POST",
url: document.URL,
data: post_data,
dataType: "text",
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(this.interval); // ????
}
}
});
return false;
}
function ajaxGetDatabase(Div,ips,interval){
$.each(ips,function(i,val){
dbs[val]=new Array();
$('#bck_action').val('get_DB');
$('#server_ip').val(val);
post_data = $('#'+Div+' *').serialize();
// console.log(post_data);
$.ajax({
type: "POST",
url: document.URL,
data: post_data,
dataType: "text",
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
}
else
{
setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
}
});
});
return false;
}
我稱之為:
ajaxGetDatabase('tab_backup',ips,3000);
var timer = null;
function ajaxGetServerDatabase(Div,val,interval){
//...
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(timer); // ????
}
//....
else
{
timer = setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
clearInterval
與ajax
無關。 這只是一個計時器函數,其作用范圍是清除之前用setInterval
設置的計時器。 如果您確實想使用計時器函數,則需要將一個變量附加到setInterval
函數,您可以使用clearInterval
設置作為參數清除setInterval
先前定義的id。
var id = " ";
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(id);
}
else
id= setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
或者,您可以使用ajax abort
中止代碼。
也許與此接近?
...
var stopAjax = 0; //switch is on
if(stopAjax == 0){
$.ajax({
...
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response);
stopAjax = 1; //switch is off
}
else{
setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
}
});
}
這是答案:在ajaxGetDatabase中:
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
}
else
{
id=setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"')", interval);
}
在ajaxGetServerDatabase中:
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(id);
}
}
不含范圍參數
var id;
為了使它變得通用並在多個服務器停止工作(多個ajax請求失敗)的情況下,我使用了一個數組來保存ID,如下所示:
var ids=new Array();
ids[val]=setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"')", interval);
clearInterval(ids[val]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.