问题
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 Genric. 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");
回答1:
The 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.
回答2:
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.
回答3:
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.com/ocovoq/3/edit#preview
回答4:
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");
};
来源:https://stackoverflow.com/questions/9740939/how-to-know-if-there-is-any-ajax-request-and-ajax-success