【问题标题】:Stop $.ajax on beforeSend在 beforeSend 上停止 $.ajax
【发布时间】:2012-05-17 10:28:31
【问题描述】:

我有这个 jQuery ajax 调用:

$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(){
        if(1 == 1) //just an example
        {
            return false
        }
    },
    complete: function(){
        console.log('DONE');
    }
});

如果条件返回true,我想停止beforeSend下的ajax调用,但return false不会停止ajax调用。

我如何在beforeSend 上进行stop ajax 调用?

======= 更新 =========

return false 也可以。

【问题讨论】:

标签: jquery ajax


【解决方案1】:
$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr, opts){
        if(1 == 1) //just an example
        {
            xhr.abort();
        }
    },
    complete: function(){
        console.log('DONE');
    }
});

【讨论】:

  • 如果您使用$(document).on("ajax:beforeSend", ".my-selector", function(e, xhr) { … }),请注意xhr 参数是第二个。
【解决方案2】:

大多数 jQuery Ajax 方法返回一个 XMLHttpRequest(或等效的)对象,因此您可以只使用 abort()。

var test = $.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(){
        if(1 == 1) //just an example
        {
            test.abort();
            return false
        }
    },
    complete: function(){
        console.log('DONE');
    }
});

【讨论】:

  • 这里有一个危险的假设,即在 ajax 方法返回之前不会调用 beforeSend。您将使用 beforeSend 的对象传递给 ajax 方法,因此 ajax 方法可以在返回设置 test 值之前很久就调用它。如果 ajax 方法同步调用 beforeSend(即在它返回任何内容之前),则在 beforeSend 运行时 test 将没有值。那将是一个错误。在传递给 beforeSend 的 jqXHR 对象上调用 abort 会更安全,就像这个线程中的另一个答案一样。
【解决方案3】:
beforeSend:function(jqXHR,setting)
{
    // if(setting.url != "your url") jqXHR.abort();
    if(1 == 1) //just an example
    {
        jqXHR.abort();
    }
}

【讨论】:

    【解决方案4】:

    xhr.done(); 这对我有用

    $.ajax({
        url : 'my_action',
        dataType: 'script',
        beforeSend : function(xhr){
            if(1 == 1) //just an example
            {
                return false
            };
            xhr.done(); //this works for me
        },
        complete: function(){
            console.log('DONE');
        }
    });
    

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

    jqXHR.done(function( data, textStatus, jqXHR ) {});
    

    成功回调选项的替代构造,请参阅deferred.done()了解实现细节。

    【讨论】:

      猜你喜欢
      • 2013-04-09
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多