jQuery ajax() 使用成功、错误和完成 vs .done()、.fail() 和 always()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18264237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery ajax() using success, error and complete vs .done(), .fail() and always()
提问by PostureOfLearning
The questions:
问题:
- Should we change our coding as suggested below?
- Is there a difference between
.done()
&success:
,.fail()
&error:
and.always()
&complete:
?
- 我们是否应该按照下面的建议更改我们的编码?
.done()
&success:
,.fail()
&error:
和.always()
&之间有区别complete:
吗?
The preamble:
序言:
I was putting together a jQuery.ajax call, which I have done successfully in the past too. Something like this:
我正在组合一个 jQuery.ajax 调用,我过去也成功地完成了这个调用。像这样的东西:
$.ajax(
{
url: someUrl,
type: 'POST',
data: someData,
datatype: 'json',
success: function (data) { someSuccessFunction(data); },
error: function (jqXHR, textStatus, errorThrown) { someErrorFunction(); }
});
While taking a quick look at some documentation, I came across a reference stating that The success, error and complete callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
在快速浏览一些文档时,我发现了一个参考资料,指出从 jQuery 1.8 开始不推荐使用成功、错误和完整回调。要为最终删除代码做好准备,请改用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always()。
We should therefore start coding something like this instead:
因此,我们应该开始编写这样的代码:
$.ajax( "example.php" )
.done(function (data) { someSuccessFunction(data); })
.fail(function (jqXHR, textStatus, errorThrown) { someErrorFunction(); })
.always(function() { alert("complete"); });
采纳答案by Esailija
Well there is no advantage of doing that in that particular situation.
那么在这种特殊情况下这样做没有任何好处。
The point of the .done()
.fail()
.always()
methods is that you can
这些.done()
.fail()
.always()
方法的重点是你可以
- Attach multiple handlers
- Do so anywhere and not just when calling
$.ajax
- 附加多个处理程序
- 在任何地方都这样做,而不仅仅是在打电话时
$.ajax
If you are at the $.ajax
call site only attaching single handlers then those advantages don't really come into play.
如果您在$.ajax
呼叫站点仅附加单个处理程序,那么这些优势并不会真正发挥作用。
So you can return the promise and others may attach their own handlers.
所以你可以返回承诺,其他人可能会附加他们自己的处理程序。
Example is refreshing plugins after ajax request:
示例是在 ajax 请求后刷新插件:
$.ajaxPrefilter(function(opt, origOpt, jqxhr) {
jqxhr.always(function() {
$("[data-plugin]").plugin();
});
});