我正在尝试为以下场景创建一个 javascript 对象
一项调查采访了多人,了解他们在几餐中食用的食物。对象需要嵌套如下:-
case={}
case[x].Interview={}
case[x].Interview[y].meals={}
case[x].Interview[y].meals[z].Food=[]
我通过以下代码实现了这一点
var $caseoffset=0
loadcases()
function loadcases() {
$.ajax({
url: "functions.php",data: {offset: $caseoffset,method: "getCase"},method: "post",dataType: 'json',
success: function(result) {
cases = result;
loadinterview(cases[$caseoffset].fldCaseID)
}
})
}
function loadinterview($CaseID) {
$.ajax({
url: "functions.php",
data: {method: "getinterview",caseid: $CaseID}, method: "post",dataType: 'json',
success: function(result) {
thiscase=cases[$caseoffset]
thiscase.interviewcount=result.length
thiscase.interviews={}
$.each(result,function(key,val){
thiscase.interviews[val.fldInterviewID]=val
loadmeals(val.fldInterviewID)
})
}
})
}
function loadmeals($InterviewID) {
$.ajax({
url: "functions.php",
data: {method: "getmeal",InterviewID: $InterviewID},method: "post",dataType: 'json',
success: function(result) {
thiscase.interviews[parseInt($InterviewID)].mealcount = result.length
thiscase.interviews[parseInt($InterviewID)].meals={}
$.each(result, function(key, val) {
thiscase.interviews[parseInt($InterviewID)].meals[parseInt(val.fldMealHistoryID)] = val
getfoodinmeal($InterviewID, val.fldMealHistoryID)
})
}
})
}
function getfoodinmeal($interviewid, $mealid) {
$.ajax({
url: "functions.php",data: {method: "getfoodinmeal",mealid: $mealid},
method: "post",
dataType: 'json',
success: function(result){
foodinmeal = [];
$.each(result, function(key, val) {
foodinmeal.push(val.fldFoodID)
})
thiscase.interviews[$interviewid].meals[$mealid].food = foodinmeal
}
})
}
问题是,一旦每位面试官食用的所有食物都已编制完毕,我想进行一些计算。我如何创建延迟语句来解决这个问题。
最佳答案
从 jQuery 1.5 开始,$.ajax()
返回一个实现 Promise 接口(interface)的 jqXHR
。
这意味着您可以将它与 Promise.all()
( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all ) 结合使用
像这样的东西应该可以工作:
Promise.all([
$.ajax({
url: "a.php"
}),
$.ajax({
url: "b.php"
}),
$.ajax({
url: "c.php"
}),
]).then(function() {
// the 3 $ajax() call are finished
})
关于javascript - 将 jQuery Deferred 与包含 $.each 的多个 ajax 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934191/