The "new" way to do this is because jQuery 1.5 (January 2011) is to use deferred objects instead of passing the success callback. You must return the result of $.ajax , and then use the methods .done , .fail , etc. to add callbacks outside the call to $.ajax .
function getData() { return $.ajax({ url : 'example.com', type: 'GET' }); } function handleData(data /* , textStatus, jqXHR */ ) { alert(data);
This separates callback processing from AJAX processing, allows you to add multiple callbacks, fail-safe callbacks, etc., without having to change the original getData() function. Separating AJAX functionality from a set of actions that need to be completed afterwards is good!
Deferrals can also greatly simplify the synchronization of several asynchronous events, which is not easy to do with success:
For example, I could add a few callbacks, an error handler, and wait for the timer to finish before continuing:
Other parts of jQuery also use deferred objects โ you can very easily synchronize jQuery animations with other async operations with them.
Alnitak Feb 07 '13 at 15:22 2013-02-07 15:22
source share