我正在尝试检查HEAD请求https://gdata.youtube.com/feeds/api/videos/<videoID>
的YouTube死视频。
现在,这些都是快速而全部的,但是它们将以403和404失败:
HEAD https://gdata.youtube.com/feeds/api/videos/XmQR4_hDtpY 404 (Not Found)
这些错误似乎使事情变得困惑。
我找到了Multiple ajax calls inside a each() function.. then do something once ALL of them are finished? - Stack Overflow并尝试使用this answer:
var videoIDs = ['a9KvHnHQVTc', 'XmQR4_hDtpY', 'WelBUaf5qsw', 'Mcrt9LJkGT4', 'P9qTLa2DVR8'];
var calls = [];
var deadVids = [];
$.each(videoIDs, function(index, value) {
calls.push($.ajax({
type: "HEAD",
url: "https://gdata.youtube.com/feeds/api/videos/" + value,
error: function() {
deadVids.push('https://www.youtube.com/watch?v=' + value + " is dead!");
}
}));
});
$.when.apply($, calls).always(function(){
console.log(deadVids.length);
});
使用
.then
,它根本不会记录deadVids.length
(= 4 ),而使用.always
或.fail
,则它会在第一个错误之后记录 1 。所有请求完成后,即使有错误,我该怎么办?
(最终,此代码将在reddit.com
$.fn.jquery -> "2.1.1"
上作为书签运行。)编辑:这似乎可以解释为什么它只记录 1 :
done
回调。 fail
回调。 通过http://afgomez.es/blog/better-ajax-callbacks-with-jquery-promises/
编辑2:使用附加到
.ajaxStop()
的全局Ajax事件处理程序document
会在所有AJAX请求结束时记录 4 $( document ).ajaxStop(function() {
console.log(deadVid);
});
编辑3 :建议使用.always(),但它对我不起作用...它将在第一个错误后触发。我使用的是Chrome 38,但是当我尝试使用Firefox 33时,它可以按预期工作,在完成所有AJAX请求后记录日志(1个OK和4个失败,记录4个)。这是一个错误吗?
最佳答案
您仅在上次调用时指定成功功能。
尝试
$.when.apply($, calls).then(function() {
console.log(deadVid);
}, function(){
//log failed
});
关于javascript - .each()中的多个AJAX调用,即使有多个错误,也要一劳永逸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26671328/