2

我已经阅读了很多关于此的帖子,但仍然无法解决我的问题。我看过 jQuery.when 但不知道如何使用它。我通过 ajax 从服务器获取数据,然后更新页面。有时,可能需要几秒钟,具体取决于返回的数据量。我不希望在页面上加载所有 html 之前运行相同的 ajax 函数。那可能吗?

我有一个计时器来运行一个调用 ajax 请求的函数。

setInterval( "update()", 25000 ); 

这是更新函数里面的ajax

                    $.ajax({
                            type: "POST",
                            url: "/ajax/modify.php",
                            data: "id="+ id +"& action="+ act,
                            success: function(response){
                                //update the html on the page
                            }           
                    }); 

用户可以通过单击链接获得更多帖子。问题是,如果他们单击该链接以获取更多帖子并且计时器立即发生,它会刷新页面并中断用户请求并使用之前的内容重新加载 div 容器。所以我需要它等到响应完成并且页面已经更新,然后才能允许更多请求。

一个值得赞赏的例子。

4

2 回答 2

3

JQuery 的 ajax 方法返回一个 Promise,您可以使用它来附加回调。您可以将此承诺存储到变量中。在函数成功/失败时,您可以清除变量。这样您就知道请求当前是否处于活动状态。只需确保变量在函数范围之外,否则它不会对您有任何帮助。例如:

var currentRequest = null;

function doUpdate() {
    // don't do anything if there's an active request
    if (currentRequest)
        return;

    currentRequest = $.ajax({
        type: "POST",
        url: "/ajax/modify.php",
        data: "id="+ id +"& action="+ act
    }).then(function(response) {
        // do your UI updates here.
    }).always(function() {
        // whether the call succeeds or not, still clear out the request
        // so that the next call into the function makes a new request
        currentRequest = null;
    });
}
于 2013-02-15T07:00:27.657 回答
0

看看这个 SO question jQuery deferreds and promises - .then() vs .done()

jQuery 延迟对象


这样做async:false会杀死它的目的,您可以在第一个成功回调中触发下一个 ajax 请求,但这不是一个干净的方法 IMO

于 2013-02-15T06:54:43.483 回答