【问题标题】:Pause and resume ajax repeated request暂停和恢复ajax重复请求
【发布时间】:2018-03-07 14:04:30
【问题描述】:

为了编写 Wiktor (https://stackoverflow.com/a/43338063/7666076) 发布的代码,如何在单击某个按钮(“暂停”和“播放”等两个不同的按钮)后暂停和恢复发送 ajax 请求。

还有如何在单击“暂停”按钮后立即中断当前的 ajax 请求。我不想等待将由 ajax 查询获取的新数据。

这是我改编的代码:

function RefreshData()
{
    console.log('Sending AJAX request...');
    $.ajax({
        type: "GET",
        url: "getAjaxRequest.php?"+device+"&callback=?",
        dataType: "jsonp"
    }).done(function(dataJSON) {
        adaptJsonData(dataJSON);
        console.log('success');
    }).fail(function() {
        console.log('error');
    }).always(function() {
        intervalTime = 100;
        console.log('Waiting '+intervalTime+' miliseconds...');
        setTimeout(RefreshData, intervalTime);
    });

    return true;
}

function adaptJsonData(dataJSON) {
    # ... some logic with dataJSON object
}

【问题讨论】:

  • $.ajax(... 赋值给一个变量,然后您可以像foo.abort() 一样中止正在进行的请求。

标签: javascript jquery ajax


【解决方案1】:
var xhr = null;
function RefreshData() {
    if( xhr != null ) {
       xhr.abort();
        xhr = null;
    }
    xhr = $.ajax({'...'});
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关其解决问题的方式和原因的额外上下文将提高​​答案的长期价值。
【解决方案2】:

Beneris 的答案非常适合中止当前的 $.ajax 请求,但这不能解决 .always 函数中的 setTimeout(function, time) 用法。

所以我通过以下方式解决了我的问题:

  1. 定义全局变量: var xhr = null - 处理 ajax xhr 对象,以及 var timer - 处理 setTimeout 引用。

  2. 按照 Beneris 的建议,将 $.ajax({...}) 分配给 xhr 变量:

var xhr = null; // global variable
var timer; // global variable
function RefreshData() {
    xhr = $.ajax({...});
}
  1. .always() 方法中赋值timer 引用setTimeout()
xhr = $.ajax({})
    .done(function(){})
    .fail(function(){})
    .always(function(){
        timer = setTimeout(RefreshData, 100);//refresh every 100 msec
    });
  1. 现在我可以通过以下方式使用 jQuery 操作 ajax 请求:
$('button.pause').click(function() {
    xhr.abort(); // xhr is in global scope; remove/comment this line if You don't need to abort last ajax request
    xhr = null; // remove/comment this line too if You don't need to abort last ajax request
    clearTimeout(timer); // timer variable is the reference to setTimeout
});
$('button.resume').click(function() {
    RefreshData();
});

如果有人需要这个功能 在不中止最后一个 ajax 请求的情况下,只需删除行 xhr.abort()

它是如何工作的?

中止当前的ajax请求:

$.ajax() 函数返回它的 XMLHttpRequest 对象 创建。通常 jQuery 处理这个对象的创建 内部,但用于制造的自定义功能可以是 使用 xhr 选项指定。返回的对象一般可以是 被丢弃,但确实提供了一个较低级别的接口用于观察和 操纵请求。特别是,调用 .abort() 对象将在请求完成之前停止请求。

http://api.jquery.com/jquery.ajax/

销毁停止刷新的setTimeout方法:

要清除一些setTimeout 的东西,只需使用clearTimeout(<the_setTimeout_reference>)

https://www.wittysparks.com/forums/topic/how-to-kill-or-cancel-or-remove-settimeout-with-cleartimeout/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 2013-07-19
    • 2015-07-28
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多