打电话到jQuery的阿贾克斯 - .fail对比:错误 [英] Call to jquery ajax - .fail vs. :error
问题描述
哪一个我应该使用?
是否有任何理由使用一个而不是其他?
是一个更好的错误处理?
$。阿贾克斯({
网址:网址,
数据:{开始:开始,结束:结束}
})。完成(功能(数据,textStatus,jqXHR){
$('#myElement')追加(数据)。
}),失败(函数(){
//报告错误
});
或
$。阿贾克斯({
网址:网址,
数据:{开始:开始,结束:结束},
成功:功能(数据,textStatus,jqXHR){
$('#myElement')追加(数据)。
},
错误:函数(jqXHR,textStatus,errorThrown){
//报告错误
}
});
这两个选项是相同的。
不过,许式接口( .fail()
和 .done()
)允许您分开code创建从code处理响应该请求。
您可以编写发送一个AJAX请求,并返回jqXHR对象中的函数,然后在其他地方调用该函数,并添加一个处理程序。
在与 .pipe组合()
函数,许式界面还可以帮助做多个AJAX时减少嵌套调用:
$。阿贾克斯(...)
.pipe(函数(){
返回$阿贾克斯(...);
})
.pipe(函数(){
返回$阿贾克斯(...);
})
.pipe(函数(){
返回$阿贾克斯(...);
});
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
}
});
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.
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.
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的阿贾克斯 - .fail对比:错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!