【发布时间】:2018-06-19 17:45:11
【问题描述】:
我正在尝试为以下场景创建一个 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
}
})
}
问题是我想在每个面试官消耗的所有食物都编译后进行一些计算。我如何创建延期声明来解决这个问题。
【问题讨论】:
-
你为什么不使用 fetch?如果可能的话,你真的应该避免 jquery ajax 调用,这样你就可以轻松地链接你的承诺developer.mozilla.org/en-US/docs/Web/API/Fetch_API | developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
-
你的问题不清楚
-
罗伯特,我现在已经修改了 php 代码,这样就不需要在 ajax 中循环了。在示例中,我提供了如何使用 fetch 而不是 ajax 进行调用。
-
如果您尝试并行获取多个案例,那么使用这样的全局
thiscase变量是不安全的
标签: javascript jquery jquery-deferred