问题
I'm working with asp controls and I have some dropdownlist which in selection go back to the server and do some action ( via asp ajax ) what I'm l looking for is detecting via jquery when the ajax call is starting I've tried the following call :
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
alert("ok");
return false;
}
});
and
also $(document).ajaxStart(function () {
alert("OK");
});
but none of this worked
回答1:
well, if $(document).ajaxStart(function() {});
is not working for you,
try a bit raw js,
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if(realXHR.readyState==1){
alert('server connection established');
}
if(realXHR.readyState==2){
alert('request received');
}
if(realXHR.readyState==3){
alert('processing request');
}
if(realXHR.readyState==4){
alert('request finished and response is ready');
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
it should give you all the states of a ajax request and check which one works for you, and then u can remove rest of the if conditions. you can place it outside of $(document).ready(function(){});
回答2:
It's really not recommended, but you can use the .ajaxStart() and .ajaxComplete() handlers:
$(document).ajaxStart(function() {
console.log('Ajax call started');
$("#loading").show();
});
$(document).ajaxComplete(function() {
console.log('Ajax call completed');
$("#loading").hide();
});
Important note Starting with jQuery 1.9, all the handlers for the jQuery global Ajax events must be attached to
document
.
Keep in mind that if your ajax call includes global: false
, the request will ignore the call default global configurations (which also means the the .ajaxStart()
and .ajaxComplete()
callbacks will not be called.
If you don't want to set the global callbacks you can set them specifically to the ajax call you make:
$.ajax({
method: "GET", // or POST
url: "path",
....
beforeSend: function() {
console.log('Ajax call started');
$("#loading").show();
},
complete: function() {
console.log('Ajax call completed');
$("#loading").hide();
}
});
回答3:
You can show your loader / waiting image
in ajax request in this way.
$('#loading-image').show();
$.ajax({
url: uri,
cache: false,
success: function(html){
$('.info').append(html);
},
complete: function(){
$('#loading-image').hide();
}
});
If you want to bind global events
like ajaxStart
and ajaxStop
.
$("#loading").bind("ajaxStart", function(){
$(this).show();
}).bind("ajaxStop", function(){
$(this).hide();
});
来源:https://stackoverflow.com/questions/39871361/detect-ajax-request-by-jquery