How can I cancel all subsequent success callbacks from a jQuery ajax success handler?
I am using jQuery 1.5.2 and have multiple success callbacks registered to an Ajax request. In the first success callback I need to check if the response has all of the data that I need, and cancel all subsequent success callbacks if it doesn't.
Note: I don't have access to the headers sent by the server. It always sends a 200 Success
.
Sec开发者_StackOverflow社区ond Note: I can't just combine the two callbacks. This is a simplified example of a problem that I have with a larger system that registers callbacks in different locations in the code.
How can I cancel the subsequent success callbacks?
Some sample code looks like this (jsfiddle):
var request = $.ajax({
url: '/echo/json'
});
// First success handler
request.done(function(data, textStatus, jqXHR) {
console.log('first', jqXHR);
if ($.isEmptyObject(data)) {
// I want to cancel the second success handler here!
}
});
// Second success handler
request.done(function(data, textStatus, jqXHR) {
console.log('second', jqXHR);
});
Thank you!
In your callback functions the first thing you should do is check for a state variable (or 'flag'), which will inform the function if it can execute or not, given the current situation.
Don't want the callbacks to execute anymore? Set the flag to some value and let the callback functions return immediately if that flag has that particular value when they get executed.
Or you could decide only to run XX callbacks and no more, or just pause them.
If you set up a system like this, you can control from a single place the behavior of larger web applications with multiple asynchronous callbacks, it will give you a lot of flexibility and options.
To aid you in this, you can have a function acting as a dispatcher. This function will be used as a callback function every time you want to alter the behavior of the callbacks. You will pass the normal callback function to call as a parameter, then the dispatcher will check for the right condition before deciding to proceed with the normal callback or not.
This way you don't need to check for the conditions right inside the callback functions. It's especially helpful for large applications with really many callbacks.
Just merge.
// Success handler
request.done(function(data, textStatus, jqXHR) {
console.log('first', jqXHR);
if ($.isEmptyObject(data)) {
return;
}
else {
console.log('second', jqXHR);
}
});
Or Try this:
var request = $.ajax({
url: '/echo/json'
});
second = true;
// First success handler
request.done(function(data, textStatus, jqXHR) {
console.log('first', jqXHR);
if ($.isEmptyObject(data)) {
second = false;
}
});
// Second success handler
request.done(function(data, textStatus, jqXHR) {
if(second)
console.log('second', jqXHR);
});
Fiddle: http://jsfiddle.net/maniator/zGvPW/3/
精彩评论