调用 jquery ajax - .fail 与 :error
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13168572/
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
Call to jquery ajax - .fail vs. :error
提问by PeteGO
Which one should I use?
我应该使用哪一种?
Is there any reason to use one rather than the other?
有什么理由使用一种而不是另一种吗?
Is one better for error handling?
一种更适合错误处理吗?
$.ajax({
url: url,
data: { start: start, end: end }
}).done(function(data, textStatus, jqXHR) {
$('#myElement').append(data);
}).fail(function() {
// report error
});
OR
或者
$.ajax({
url: url,
data: { start: start, end: end },
success: function(data, textStatus, jqXHR) {
$('#myElement').append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// report error
}
});
采纳答案by SLaks
The two options are equivalent.
这两个选项是等效的。
However, the promise-style interface (.fail()
and .done()
) allow you to separate the code creating the request from the code handling the response.
但是,promise 风格的接口(.fail()
和.done()
)允许您将创建请求的代码与处理响应的代码分开。
You can write a function that sends an AJAX request and returns the jqXHR object, and then call that function elsewhere and add a handler.
您可以编写一个发送 AJAX 请求并返回 jqXHR 对象的函数,然后在别处调用该函数并添加一个处理程序。
When combined with the .pipe()
function, the promise-style interface can also help reduce nesting when making multiple AJAX calls:
与该.pipe()
函数结合使用时,promise 风格的界面还可以帮助减少进行多次 AJAX 调用时的嵌套:
$.ajax(...)
.pipe(function() {
return $.ajax(...);
})
.pipe(function() {
return $.ajax(...);
})
.pipe(function() {
return $.ajax(...);
});
回答by slohr
Just to freshen this up...
只是为了让这个焕然一新......
The success and error approach have been deprecated as of jQuery 1.8.
从 jQuery 1.8 开始,成功和错误方法已被弃用。
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.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.
弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 1.8 开始弃用。要为最终删除代码做好准备,请改用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always()。
回答by ow3n
Using the chainable deferred objectpromise style allows for a cleaner structure and the use of always.
使用可链接的延迟对象承诺样式允许更清晰的结构和always的使用。
let data = {"key":"value"}
$.ajax({
type: 'PUT',
url: 'http://example.com/api',
contentType: 'application/json',
data: JSON.stringify(data),
}).done(function () {
console.log('SUCCESS');
}).fail(function (msg) {
console.log('FAIL');
}).always(function (msg) {
console.log('ALWAYS');
});