【发布时间】:2017-12-12 21:29:02
【问题描述】:
我的回调函数有问题。我的代码应该向 REST API 发出 16 个 GET 请求以提取 16 个不同的 JSON 文件。然后,它需要将这些 JSON 中的每一个解析为一个字典,用于该周的足球桌排名,并最终将每个条目保存到一个“字典字典”HistoricalTable 中,以提供过去 16 周的联赛排名。但是,当我运行相关的回调函数时,各种 LeagueTable 变量似乎工作正常,但当我尝试将这些变量保存到历史数据中时,最终数组似乎每个都有相同的 LeagueTable 条目,如下所示。
//This creates the modifier for the URL used in the GET request
var MatchDayList = []
for (i = 0; i < 17; i++) {
MatchDayList[i] = i
}
MatchDayList.shift()
var HistoricalTable = {}
var LeagueTable = {}
// This executes the GET request
for (i = 0; i < 16; i++) {
url = 'http://api.football-data.org/v1/competitions/445/leagueTable/?matchday=' + MatchDayList[i],
$.ajax({
url: 'http://api.football-data.org/v1/competitions/445/leagueTable/?matchday=' + MatchDayList[i],
headers: {
'X-Auth-Token': ''
},
method: 'GET',
dataType: 'json',
success: function(data) {
handleData(data)
},
});
}
//This function should append the retrieved JSON to the LeagueTable variable
function handleData(data) {
for (var j = 0; j < 20; j++) {
LeagueTable[data.standing[j].position] = data.standing[j].teamName
LeagueTable[20] = data.matchday
}
saveData(LeagueTable)
}
//This function should save each LeagueTable matchday data into a bigger array, HistoricalTable
function saveData(LeagueTable) {
HistoricalTable[LeagueTable[20]] = LeagueTable
console.log(HistoricalTable)
}
【问题讨论】:
标签: javascript jquery json callback get