Disable ajaxStart() and ajaxStop() for a specific request

China☆狼群 提交于 2019-11-28 03:05:32

I figured it out..

There is an attribute in the options object .ajax() takes called global.

If set to false, it will not trigger the ajaxStart event for the call.

$.ajax({
    timeout: 35000,
    url: longPollUrl,
    success: function(data){
        if(data.queCount) $('#numQueCount').html(data.queCount);
        if(data.queAccept) $('#numQueAccept').html(data.queAccept);
    }, 
    global: false,     // this makes sure ajaxStart is not triggered
    dataType: 'json',
    complete: longpoll
});

After reading all possible solutions, I want to combine answers.

Solution 1: Bind/Unbind

//binding
$(document).bind("ajaxStart.mine", function() {
    $('#ajaxProgress').show();
});

$(document).bind("ajaxStop.mine", function() {
    $('#ajaxProgress').hide();
});

//Unbinding
$(document).unbind(".mine");

It is a depreciated solution. Before jQuery 1.9, global events of ajax like ajaxStart, ajaxStop, ajaxError etc. can be binded to any element. After jQuery 1.9:

As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with the .ajaxStart() method, must be attached to document.

Therefore we cannot bind/unbind these events to custom namespaces.

Solution 2: Set the property global to false

$.ajax({
        url: "google.com",
        type: "GET",
        dataType: "json",
        global: false, //This is the key property.
        success: function (data) {
                   console.log(data);
                },
        error: function (data) {
                   console.log(data);
                }
       });

This solution works to disable ajaxStart()/ajaxStop() event(s). However, it also makes disable ajaxComplete(), ajaxError(), ajaxSend(), ajaxSuccess(). If you don't use these global events, it seems ok, but when it is needed, you have to come back and change your solution for all pages where you set global: false.

Solution 3: Use global variable

var showLoadingEnabled = true;
$(document).ready(function () {
    $('#loading')
        .hide()  // at first, just hide it
        .ajaxStart(function () {
            if (showLoadingEnabled) {
                $(this).show();
            }
        })
        .ajaxStop(function () {
            if (showLoadingEnabled) {
                $(this).hide();
            }
        });
});


function justAnotherFunction() {
    window.showLoadingEnabled = false;
    $.ajax({
        url: 'www.google.com',
        type: 'GET',
        complete: function (data) {
            window.showLoadingEnabled = true;
            console.log(data);
        }
    });
}

Global variables should not be used in javascript files. However, this is the simplest solution, I can find.

I prefered the third solution for my project.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!