admin管理员组文章数量:1292699
I wonder how can I code this:
//if there is any ajax request
$("#loader").css("display","block");
//on success:
$("#loader").css("display","none");
Note :
I am not going to code it again and again in my each ajax request function.
I want it generic so that my script knows if there is any ajax request do $("#loader").css("display","block");
and if there is any ajax success do $("#loader").css("display","none");
.
I wonder how can I code this:
//if there is any ajax request
$("#loader").css("display","block");
//on success:
$("#loader").css("display","none");
Note :
I am not going to code it again and again in my each ajax request function.
I want it generic so that my script knows if there is any ajax request do $("#loader").css("display","block");
and if there is any ajax success do $("#loader").css("display","none");
.
4 Answers
Reset to default 8The magical thing you are looking for is jQuery.ajaxStart() and jQuery.ajaxStop(). You might also find jQuery.ajaxComplete() useful.
Example:
$("#loader").ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
You should use the hide()
and show()
methods instead of changing the display
CSS attribute.
Take a look at $.ajaxStart
and $.ajaxEnd
when you wire up your app in $.document(ready):
$.ajaxStart(function(){
$("#loader").css("display", "block");
})
.ajaxStop(function(){
$("#loader").css("display", "none");
});
UPDATE forgot about ajaxStop...@Cory's answer reminded me. Updated my answer.
These other solutions are great but I am not sure they address your concern of calling your $("#loader")
CSS changes on start and success.
May be something like this:
$(document).ajaxStart(function() {
// do something on start
$("#loader").css("display","block");
}).ajaxError(function(e, xhr, settings) {
// do something on error
$("#loader").css("display","none");
}).ajaxSuccess(function() {
// do something on success
$("#loader").css("display","block");
});
Check out this properly working example: http://jsbin./ocovoq/3/edit#preview
If you fire off two or three ajax calls, ajaxStop will only fire when the last one is done.
var isMakingAjaxCall;
$(document).ready(function () {
// Loading Screen for Ajax Calls
$("#loader").hide();
$("#loader").ajaxStart(function () {
isMakingAjaxCall = true;
RepositionLoading();
$("#loader").fadeIn();
});
$("#loader").ajaxStop(function () {
$("#loader").fadeOut();
isMakingAjaxCall = false;
});
});
function RepositionLoading() {
$("#loader").css('left', "20px");
$("#loader").css('top', "20px");
};
本文标签: javascriptHow to know if there is any Ajax Request and ajax SuccessStack Overflow
版权声明:本文标题:javascript - How to know if there is any Ajax Request and ajax Success - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741560412a2385412.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论