在beforeSend上停止$ .ajax

Mr_*_*zle 41 ajax jquery

我有这个jQuery ajax调用:

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

我想在beforeSendif条件返回的情况下停止ajax调用true但返回false不会停止ajax调用.

我怎么能stop在ajax上调用beforeSend

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

return false 也有效.

the*_*dox 74

$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr, opts){
        if(1 == 1) //just an example
        {
            xhr.abort();
        }
    },
    complete: function(){
        console.log('DONE');
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 如果你使用`$(document).on("ajax:beforeSend",".my-selector",function(e,xhr){...})`,请注意`xhr`参数是第二个. (3认同)

Far*_*mad 10

大多数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');
    }
});
Run Code Online (Sandbox Code Playgroud)


The*_*pha 6

beforeSend:function(jqXHR,setting)
{
    // if(setting.url != "your url") jqXHR.abort();
    if(1 == 1) //just an example
    {
        jqXHR.abort();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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');
    }
});
Run Code Online (Sandbox Code Playgroud)

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

jqXHR.done(function( data, textStatus, jqXHR ) {});
Run Code Online (Sandbox Code Playgroud)

成功回调选项的替代构造,请参阅deferred.done()有关实现的详细信息。