在特定情况下防止ajax加载动画

时间:2014-03-21 08:19:52

标签: javascript jquery ajax

我有一个全局的ajax加载动画,它在每个调用的ajax中运行。但在这种情况下,我想禁用该效果。我怎么能这样做?

这适用于全球动画:

$(document).ajaxStart(function(){
   $('#ajax-loader').show();
}).ajaxStop(function(){
   $('#ajax-loader').fadeOut(200);
});

在代码之下,我不会显示动画。

setInterval(function(){
   chat_notif(); //function that contain an ajax call
}, 1000);

2 个答案:

答案 0 :(得分:1)

您可以通过查看xhr

中的optionsajaxSend()来分开
var ajaxXhr, ajaxOptions;
$(document).ajaxSend(function(event, xhr, options) {
   ajaxXhr = xhr;
   ajaxOptions = options;
}).ajaxStart(function(){
   if(ajaxXhr || ajaxOptions ) //something that detects the specific case
    $('#ajax-loader').show();
};

jquery - Can I retrieve (event, xhr, options) from .ajaxStart or .ajaxStop?

<强>用法:

假设您想要获取网址"/rest/refreshChatNotifications",此网址将位于XHRoptions内(我猜xhr)。现在,您可以使用if中的ajaxStart来检查此网址。

var ajaxXhr, ajaxOptions, refreshChatUrl = "/rest/refreshChatNotifications";
$(document).ajaxSend(function(event, xhr, options) {
   ajaxXhr = xhr;
   ajaxOptions = options;
}).ajaxStart(function(){
   if(ajaxXhr.url !=  refreshChatUrl ) //if it's the specific url, dont show
    $('#ajax-loader').show();
};

如果您有多个网址,则不应显示动画,请按以下步骤操作:

var ajaxXhr, ajaxOptions;
var dontShowAnimationForUrls = ["/rest/refreshChatNotifications", "/rest/anotherAjaxWithoutLoader"];
$(document).ajaxSend(function(event, xhr, options) {
   ajaxXhr = xhr;
   ajaxOptions = options;
}).ajaxStart(function(){
   if(dontShowAnimationForUrls.indexOf(ajaxXhr.url) < -1) //if it's the specific url, dont show. Index will be > -1, then url found.
    $('#ajax-loader').show();
};

答案 1 :(得分:0)

也许你可以添加一个默认值为showAjaxAnimation的全局布尔变量true。在setInterval你可以做出类似的事情。

setInterval(function(){
   showAjaxAnimation = false;
   chat_notif(); //function that contain an ajax call
   showAjaxAnimation = true;
}, 1000);

然后在你可以做的AjaxStart中:

$(document).ajaxStart(function(){
   if (showAjaxAnimation)
     $('#ajax-loader').show();
}).ajaxStop(function(){
   $('#ajax-loader').fadeOut(200);
});