调用 jquery ajax - .fail 与 :error [英] Call to jquery ajax - .fail vs. :error
问题描述
我应该使用哪个?
是否有任何理由使用一种而不是另一种?
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
});
或
$.ajax({
url: url,
data: { start: start, end: end },
success: function(data, textStatus, jqXHR) {
$('#myElement').append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// report error
}
});
推荐答案
这两个选项是等价的.
但是,promise 风格的接口(.fail()
和 .done()
)允许您将创建请求的代码与处理响应的代码分开.
However, the promise-style interface (.fail()
and .done()
) allow you to separate the code creating the request from the code handling the response.
您可以编写一个发送 AJAX 请求并返回 jqXHR 对象的函数,然后在其他地方调用该函数并添加处理程序.
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.
当与 .pipe()
函数结合使用时,promise 风格的界面还可以帮助减少进行多次 AJAX 调用时的嵌套:
When combined with the .pipe()
function, the promise-style interface can also help reduce nesting when making multiple AJAX calls:
$.ajax(...)
.pipe(function() {
return $.ajax(...);
})
.pipe(function() {
return $.ajax(...);
})
.pipe(function() {
return $.ajax(...);
});
这篇关于调用 jquery ajax - .fail 与 :error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!