Disabling some jQuery global Ajax event handlers for a request

后端 未结 4 1467
故里飘歌
故里飘歌 2020-12-02 17:01

Suppose that I have some global Ajax event handlers defined (ajaxStart, ajaxStop, and ajaxError). Usually I am fine with that, but for one request, I want to disable the aja

相关标签:
4条回答
  • 2020-12-02 17:22

    try to use global: false in your ajax request like:

     $.ajax({
       url: "test.html",
       global: false,
       // ...
     });
    

    source:: http://docs.jquery.com/Ajax_Events

    Look for Global Events.

    0 讨论(0)
  • 2020-12-02 17:23

    It's possible and not difficult to do.

    You just need to setup your global error handler (.ajaxError) to receive a few of the parameters that jQuery can provide to it:

    $("div.log").ajaxError(function(evt, xhr, settings) {
        if(settings.suppressErrors) {
            return;
        }
    
        // Normal processing
    });
    

    After this, you can add suppressErrors: true to the settings of any AJAX request you make, and if it fails the error handler will return without doing what it normally does.

    See it in action.

    0 讨论(0)
  • 2020-12-02 17:34

    You can set $.event.global.ajaxError to false to disable invoking the global error callback temporarily. Use the error and complete callbacks of your special request to set the flags:

    $.ajax({
        url: 'some.domain.com/',
    }).error(function(jXHR){
        // Disable global error logging
        $.event.global.ajaxError = false;
    }).complete(function(){
        // Enable global error logging
        $.event.global.ajaxError = true;
    });
    

    An example is available on jsFiddle.

    That being presented, I want to add that I would still prefer Jon's proposal. This technique requires to set the flag at 2 places of which you could forget one and and up to have the global handlers disabled accidentally. The other reason is that Jon's technique should be guaranteed to work across jQuery releases where setting some internal flags is not reliable.

    0 讨论(0)
  • 2020-12-02 17:45

    When you look at this if statement from the jquery/ajax source https://github.com/jquery/jquery/blob/master/src/ajax.js#L579-582 , which is one of many of the same kind, it is clear that your problem can not be solved by a jquery parameter alone.

    My suggestion would be to:

    • set global to false, like Vaibhav Gupta said

    • map your global handlers to local in the specific ajax call and trigger the global event through the $.event.trigger method

    Sample:

    $.ajax({
        url: "test.html",
        global: false,
        beforeSend: function(){$.event.trigger('ajaxStart');},
        complete: function(){$.event.trigger('ajaxStop');},
        error: your_error_handler
    });
    
    0 讨论(0)
提交回复
热议问题