试图停止/继续ajax调用

时间:2013-08-12 16:44:41

标签: jquery ajax

    $.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);
        }
    });

.expandhide函数扩展/隐藏元素。当用户点击.expandhide(展开)并在用户再次点击它时恢复ajax调用(隐藏它)时,我需要ajax停止进一步调用。几乎就是我如何切换.infopanel,除了使用ajax来停止/继续通话。可以这样做吗?

1 个答案:

答案 0 :(得分:2)

将间隔设置为变量并在隐藏变量时将其清除:

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);  
    }
    ...
);

或者,作为快速修复,只需添加一个beforeSend匿名函数,如果.infopanel不可见,则取消发送该函数:

$.ajax(
    ...
    beforeSend: function(jqXHR, settings) {
        if ($(".infopanel").is(":hidden")) {
            return false; //Don't send the request
        }
    }
);