Jquery 尝试停止/继续ajax调用
.expandhide函数用于展开/隐藏元素。我需要ajax在用户单击后停止进一步调用。expandhide(展开)并在用户再次单击(隐藏)时恢复ajax调用。这与我切换.infopanel的方式差不多,除了使用ajax停止/继续调用。可以这样做吗?将间隔设置为变量,并在隐藏时将其清除:Jquery 尝试停止/继续ajax调用,jquery,ajax,Jquery,Ajax,.expandhide函数用于展开/隐藏元素。我需要ajax在用户单击后停止进一步调用。expandhide(展开)并在用户再次单击(隐藏)时恢复ajax调用。这与我切换.infopanel的方式差不多,除了使用ajax停止/继续调用。可以这样做吗?将间隔设置为变量,并在隐藏时将其清除: $.ajax({ type:'POST', dataType:'json', data:{ }, url:'pulldata.php',
$.ajax({
type:'POST',
dataType:'json',
data:{ },
url:'pulldata.php',
timeout:3000,
success:function (data) {
$('#thediv').html(data.html);
$(".expandhide").click(function () { // THIS IS WHERE I'M STUCK
$(this).parents().next(".infopanel").toggle(500);
});
window.setTimeout(update, 3000);
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
window.setTimeout(update, 60000);
}
});
或者,作为一种快速修复方法,只需在发送前添加一个匿名函数,如果您的.infopanel
不可见,该函数将取消发送:
var timeout = null;
var expanded = false;
var ajax = null;
$(".expandhide").click(function() {
expanded = !expanded; //Reverse it
if (expanded) {
update(); //Call update again but right away
} else {
//Abort the ongoing ajax call (if any)
if (ajax !== null) ajax.abort();
//Clear the timeout
if (timeout !== null) clearTimeout(timeout);
}
});
//Set the global "ajax" variable to our request - don't use "var" here
ajax = $.ajax(
...
success: function(data) {
// Do NOT use "var" here, as we're referencing the global variable
timeout = setTimeout(update, 3000);
}
...
);
添加一个标志变量怎么样?非常感谢!我更喜欢你的第二个解决方案。我只需要添加setTimeout,这样它就会不断检查它是否隐藏。再次感谢。
$.ajax(
...
beforeSend: function(jqXHR, settings) {
if ($(".infopanel").is(":hidden")) {
return false; //Don't send the request
}
}
);