// Assign handlers immediately after making the request,// and remember the jqxhr object for this request var jqxhr = $.post( "example.PHP",function() { alert( "success" ); }) .done(function() { alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); }); // Perform other work here ... // Set another completion function for the request above jqxhr.always(function() { alert( "second finished" ); });
解决方法
然后,他们决定支持jqXHR对象的承诺,那就是在promise API的精神中添加了.done(),.fail(),.always()等等。这些新方法与回调有很大的不同,但是以不同的形式。您可以使用任何API风格对您的编码风格更有效。
随着人们越来越熟悉承诺,随着越来越多的异步操作使用这个概念,我怀疑越来越多的人会随着时间推移到承诺API,但在此期间,jQuery支持两者。
.success()方法已被弃用,有利于常见的promise对象方法名称。
从jQuery doc,您可以看到各种承诺方法与回调类型相关:
jqXHR.done(function( data,textStatus,jqXHR ) {}); An alternative
construct to the success callback option,the .done() method replaces
the deprecated jqXHR.success() method. Refer to deferred.done() for
implementation details.jqXHR.fail(function( jqXHR,errorThrown ) {}); An
alternative construct to the error callback option,the .fail() method
replaces the deprecated .error() method. Refer to deferred.fail() for
implementation details.jqXHR.always(function( data|jqXHR,jqXHR|errorThrown ) {
}); An alternative construct to the complete callback option,the
.always() method replaces the deprecated .complete() method.In response to a successful request,the function’s arguments are the
same as those of .done(): data,and the jqXHR object. For
Failed requests the arguments are the same as those of .fail(): the
jqXHR object,and errorThrown. Refer to deferred.always()
for implementation details.jqXHR.then(function( data,jqXHR ) {},function( jqXHR,
textStatus,errorThrown ) {}); Incorporates the functionality of the
.done() and .fail() methods,allowing (as of jQuery 1.8) the
underlying Promise to be manipulated. Refer to deferred.then() for
implementation details.
如果要以符合ES6 Promises标准的方式进行编码,那么这四个选项只能使用.then()。