取消previous Ajax请求的jQuery [英] Cancelling previous ajax request jquery

查看:100
本文介绍了取消previous Ajax请求的jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我看过的总体解决方案,这是如下:

  VAR DataRequest = $阿贾克斯({/ * ... * /});
 

然后 DataRequest.abort() beforeSend Ajax事件。然而,这导致在被发送编号的请求。

我试图做到的,是中止声明为DataRequest(例如)任何Ajax操作,并且只允许最新的请求继续进行。目前,我有一个按钮,点击时启动的请求,并增加了装载微调。如果我点击了很多次,我只是得到了一堆装纺纱填补了我的网页。我怎样才能prevent呢?

下面是相关的code:

  beforeSend:函数(){
    $('< D​​IV CLASS =网格>< / DIV>')
        .attr('身份证','装')
        。隐藏()
        .insertBefore('#输出)
        。淡入();
},

成功:功能(数据){
    $('#装载)。隐藏(函数(){
        $(本)上卸下摆臂();
    });
}
 

解决方案

下面是我使用的时候,我需要有多个请求,只处理最后一个模式:

  VAR fooXHR,fooCounter = 0;
$(...)。结合(someEvent',函数(){
  //做正确的事,表明我们并不关心请求了
  如果(fooXHR)fooXHR.abort();

  VAR令牌= ++ fooCounter;
  fooXHR = $获得(...,功能(数据){
    //要调用即使中止XHR可能导致回调
    如果(标记= fooCounter!)回报;

    //在这一点上,我们知道我们正在使用的最新请求的数据
  });
});
 

修改:我裹这个功能在一个插件式的方法调用浏览:
<一href="http://stackoverflow.com/questions/1434519/can-you-cancel-a-jquery-ajax-call-before-it-returns/5746018#5746018">Can取消一个jQuery AJAX调用返回前?

From what I've read the general solution to this is as follows:

var DataRequest = $.ajax({ /* ... */ });

and then DataRequest.abort() in the beforeSend ajax event. However, this results in NO requests being sent.

What I'm trying to achieve is to abort any ajax operations that are declared as DataRequest (for example), and allow only the latest request to proceed. Currently I have a button that when clicked starts a request and adds a loading spinner. If I click it many times, I just get a bunch of loading spinners filling up my page. How can I prevent this?

Here's the relevant code:

beforeSend: function() {
    $('<div class="grid"></div>')
        .attr('id', 'loading')
        .hide()
        .insertBefore('#output')
        .fadeIn();
},

success: function(data) {
    $('#loading').hide(function () {
        $(this).remove();
    });
}

解决方案

Here's the pattern I use when I need to have multiple requests and only process the last:

var fooXHR, fooCounter=0;
$(...).bind( 'someEvent', function(){
  // Do the Right Thing to indicate that we don't care about the request anymore
  if (fooXHR) fooXHR.abort();

  var token = ++fooCounter;
  fooXHR = $.get( ..., function(data){
    // Even aborted XHR may cause the callback to be invoked
    if (token != fooCounter) return;

    // At this point we know that we're using the data from the latest request
  });
});

Edit: I have wrapped this functionality up in a plugin-like method call here:
Can you cancel a jQuery AJAX call before it returns?

这篇关于取消previous Ajax请求的jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆