在返回之前取消jQuery AJAX调用?

Hec*_*out 24 ajax jquery

我有一个打开的jQuery对话框,然后进行AJAX调用.我想这样做,如果关闭对话框或按下取消按钮,AJAX调用将被取消,并且不会调用其回调函数.我可以想办法用这样的变量做到这一点:

  function doStuff(){
    var doCallback = true;
    $('#dialog').dialog({
      title: 'Dialog Title',
      modal: true,
      buttons: {
        Cancel: function() {
          doCallback = false;
          doSomethingElse();
        }
      }
    });
    $.get('url/url/url', function(data){
      if(doCallback){
        doTheSuccessThing(data);
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

但是,不知何故,这对我来说感觉很脏,并且实际上并没有阻止AJAX调用完成.是否有内置方法取消正在进行的AJAX调用?

Phr*_*ogz 17

当我有一个可能被多次触发的回调,但我想只使用最后一个,我使用这个模式:

var resultsXHR, resultsTimer, resultsId=0;
$('input').keyup(function(){
  clearTimeout(resultsTimer);                     // Remove any queued request
  if (resultsXHR) resultsXHR.abort();             // Cancel request in progress
  resultsTimer = setTimeout(function(){           // Record the queued request
    var id = ++resultsId;                         // Record the calling order
    resultsXHR = $.get('/results',function(data){ // Capture request in progress
      resultsXHR = null;                          // This request is done
      if (id!=resultsId) return;                  // A later request is pending
      // ... actually do stuff here ...
    });  
  },500);                                         // Wait 500ms after keyup
});
Run Code Online (Sandbox Code Playgroud)

abort()单独不足以阻止调用成功回调; 即使您尝试取消请求,您仍可能会发现回调运行.这就是为什么有必要使用resultsId跟踪器并让你的回调停止处理,如果另一个,后来重叠的回调准备就绪.

鉴于这是多么常见和繁琐,我认为以一种可重复使用的方式将其包装起来是一个好主意,这种方式不需要您为每个要处理的每个变量名称提供一个独特的三元组:

(function($){
  $.fn.bindDelayedGet = function(event,delay,url,dataCallback,dataType,callback){
    var xhr, timer, ct=0;
    return this.bind(event,function(){
      clearTimeout(timer);
      if (xhr) xhr.abort();
      timer = setTimeout(function(){
        var id = ++ct;
        xhr = $.get(url,dataCallback && dataCallback(),function(data){
          xhr = null;
          if (id==ct) callback(data);
        },dataType);
      },delay);
    });
  };
})(jQuery);

// In action
var inp = $('#myinput').bindDelayedGet('keyup',400,'/search',
  function(){ return {term:inp.val()}; },
  'html',
  function(html){ $('#searchResults').clear().append(html); }
);
Run Code Online (Sandbox Code Playgroud)

您可以在我的网站上找到更详细讨论的上述代码.


Hec*_*out 14

好的,基于使用$ .get函数返回的XmlHttpRequest对象的建议,我提出了这个:

function doStuff(){
    var ajaxRequest = $.ajax({
                        url : 'url/url/url',
                        type : "GET",
                        success : function(data){
                          ajaxRequest = null;
                          doSuccessStuff(data);
                        }
                      });

    $('#dialog').dialog({
      title: 'Stuff Dialog',
      bgiframe: true,
      modal: true,
      buttons: {
        Cancel: function() {
          if (ajaxRequest)
            ajaxRequest.abort();
          doCancelStuff();
        }
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

对我来说似乎工作和感觉更干净.

  • 不要忘记检查ajaxRequest是否为空.你应该在'success'方法中重置它 - 然后你可以判断是否有一个活跃的ajax请求 (3认同)

Tec*_*ise 5

在jQuery中没有方法,但你可以只使用从jQuery get/post/ajax函数返回的XmlHttpRequest对象.

来自jQuery博客:

// Perform a simple Ajax request
var req = $.ajax({
  type: "GET",
  url: "/user/list/",
  success: function(data) {
    // Do something with the data...
    // Then remove the request.
    req = null;
  }
});

// Wait for 5 seconds
setTimeout(function(){
  // If the request is still running, abort it.
  if ( req ) req.abort();
}, 5000);
Run Code Online (Sandbox Code Playgroud)