What is the difference between success and the .done () $ .ajax method

Can anyone help me?
I can not understand the difference between success and .done() from $.ajax .

If possible, give examples.

+86
jquery jquery-deferred
Jan 13 2018-12-12T00:
source share
4 answers

In short, decoupling the success callback from the ajax function, so you can add your own handlers later without changing the source code (observer pattern).

More details can be found here: https://stackoverflow.com/a/167268/

+9
Jan 13 2018-12-12T00:
source share

success is only triggered when an AJAX call is successful, i.e. ultimately returns HTTP status 200. error triggered if it fails, and complete when the request ends, regardless of success.

In jQuery 1.8, the jqXHR object (returned by $.ajax ) success was replaced by done , error by fail and complete by always .

However, you can still initialize the AJAX request with the old syntax. So they do similar things:

 // set success action before making the request $.ajax({ url: '...', success: function(){ alert('AJAX successful'); } }); // set success action just after starting the request var jqxhr = $.ajax( "..." ) .done(function() { alert("success"); }); 

This change is compatible with jQuery 1.5 pending object . Deferred (and now Promise , which has full browser support in Chrome and FX), allows you to chain asynchronous actions:

 $.ajax("parent"). done(function(p) { return $.ajax("child/" + p.id); }). done(someOtherDeferredFunction). done(function(c) { alert("success: " + c.name); }); 

This chain of functions is easier to maintain than the nested pyramid of callbacks you receive with success .

However, note that done now deprecated in favor of the Promise syntax, which then uses instead:

 $.ajax("parent"). then(function(p) { return $.ajax("child/" + p.id); }). then(someOtherDeferredFunction). then(function(c) { alert("success: " + c.name); }). catch(function(err) { alert("error: " + err.message); }); 

This is worth accepting, because async and await extend promises enhanced syntax (and error handling):

 try { var p = await $.ajax("parent"); var x = await $.ajax("child/" + p.id); var c = await someOtherDeferredFunction(x); alert("success: " + c.name); } catch(err) { alert("error: " + err.message); } 
+86
Jan 13 2018-12-12T00:
source share

.success() is only called if your web server responds with a 200 kilobyte HTTP header - basically when everything is ok.

Callbacks attached to done () will be fired when a request is pending. Callbacks connected to fail () will be triggered when rejected reject.

 promise.done(doneCallback).fail(failCallback) .done() has only one callback and it is the success callback 
+5
Jan 13 '12 at 8:45
source share

success is a callback that is called when the request is successful and is part of the $.ajax . done is actually part of the jqXHR object returned by $.ajax() and replaces success in jQuery 1.8.

0
Jan 13 2018-12-12T00:
source share



All Articles