我需要计算在列表中的每个项目上成功执行jQuery ajax调用的次数。
我从这里开始,但后来意识到这将无法工作,因为ajax的“异步”部分:
var numSuccessfullUpdates = 0;
$('#saveMyListItems').click(function (event) {
event.preventDefault();
$('ul#myList li').each(function () {
$.ajax({
url: '[my_url]',
type: "POST",
data: {
// [data block here, not relevant to question]
},
success: function () {
numSuccessfullUpdates++;
}
});
});
if (successfullUpdates > 0){
alert(numSuccessfullUpdates);
}
});
有什么建议吗?
答案 0 :(得分:3)
您可以尝试jQuery 1.5 +中提供的新when()
和then()
功能,
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).then(myFunc, myFailure);
这里在两个ajax请求成功时执行函数myFunc,或者如果其中一个有错误则执行myFailure。
因此,通过上述函数,您可以检查在运行myFunc
函数时是否已成功完成所有ajax请求。
答案 1 :(得分:2)
您可以使用AJ complete
处理程序并计算状态结果,直到结果总数等于请求总数。以下是示例代码also available as a jsFiddle
$('#saveMyListItems').click(function (event) {
event.preventDefault();
var ajaxCounter = {
goal: $('ul#myList li').length,
total: 0,
success: 0,
notmodified: 0,
error: 0,
timeout: 0,
abort: 0,
parsererror: 0
}
$('ul#myList li').each(function () {
$.ajax({
url: '/echo/html',
type: "POST",
timeout: 1500,
data: {
html: "foobar",
delay: Math.floor(Math.random() * 5)
},
complete: function (jqXHR, textStatus) {
ajaxCounter.total++
ajaxCounter[textStatus]++;
if (ajaxCounter.total >= ajaxCounter.goal) {
alert(ajaxCounter.success + ' out of ' + ajaxCounter.total);
}
},
});
});
});
答案 2 :(得分:0)
您还需要计算所有回复,并在达到总数或合理超时到期时发出警报。