The "new" way of doing this since jQuery 1.5 (Jan 2011) is to use deferred objects instead of passing a success
callback. You should return the result of $.ajax
and then use the .done
, .fail
etc methods to add the callbacks outside of the $.ajax
call.
function getData() {
return $.ajax({
url : 'example.com',
type: 'GET'
});
}
function handleData(data /* , textStatus, jqXHR */ ) {
alert(data);
//do some stuff
}
getData().done(handleData);
This decouples the callback handling from the AJAX handling, allows you to add multiple callbacks, failure callbacks, etc, all without ever needing to modify the original getData()
function. Separating the AJAX functionality from the set of actions to be completed afterwards is a good thing!.
Deferreds also allow for much easier synchronisation of multiple asynchronous events, which you can't easily do just with success:
For example, I could add multiple callbacks, an error handler, and wait for a timer to elapse before continuing:
// a trivial timer, just for demo purposes -
// it resolves itself after 5 seconds
var timer = $.Deferred();
setTimeout(timer.resolve, 5000);
// add a done handler _and_ an `error:` handler, even though `getData`
// didn't directly expose that functionality
var ajax = getData().done(handleData).fail(error);
$.when(timer, ajax).done(function() {
// this won't be called until *both* the AJAX and the 5s timer have finished
});
ajax.done(function(data) {
// you can add additional callbacks too, even if the AJAX call
// already finished
});
Other parts of jQuery use deferred objects too - you can synchronise jQuery animations with other async operations very easily with them.
deferred objects
thing get introduced? I haven't seen it before. Also, it seems slightly messy, since the code that defines what callback to use is in a different location than the actual AJAX call. – Levitate