【发布时间】:2023-04-11 02:56:01
【问题描述】:
谁能帮我解决以下问题。我有 2 个 JSON 文件:
names.json:包含每个人的所有姓名年龄和地址数组(如果是多个居住地)。
{ "people": [ { "name":"Peter Gabriel", "age":42, "address": ["location1","location2","location3"] }, { "name":"Mark Vincent", "age":"25", "address": ["location4","location5"] } ] }-
data.json:包含所有地址详细信息
{ "location1": { "country":"Switzerland", "street":"some Avenue", "number": 32 }, "location2": { "country":"Latvia", "street":"some Street", "number": 43 }, "location3": { "country":"Denmark", "street":"some Road", "number": 16 }, "location4": { "country":"Austria", "street":"some Avenue", "number": 54 }, "location5": { "country":"Poland", "street":"some Avenue", "number": 23 } }我需要将 data.json 文件数据放在全局中并在 names.json 之前加载,但由于 JSON 加载是一个异步函数,我该怎么做。var jsonAddressData = []; function main() { loadNamesJSON(function(response) { jsonAddressData = JSON.parse(response); }); loadNamesJSON(function(response) { var jsonPeopleData = JSON.parse(response); var addressDetail=[]; for(var i in jsonPeopleData.people){ // ACCESS ADDRESS OBJECT DETAILS HERE for(var j in jsonPeopleData.people[i].address){ if (jsonPeopleData.people[i].address[j] in jsonAddressData){ addressDetail.append(jsonAddressData[jsonPeopleData.people[i].address[j]]) } } } }); } function loadNamesJSON(callback) { var request = new XMLHttpRequest(); request.overrideMimeType("application/json"); request.open('GET', 'names.json', true); request.onreadystatechange = function () { if (request.readyState === 4 && request.status ===200) { callback(request.responseText); } }; request.send(null); } function loadDataJSON(callback) { var request = new XMLHttpRequest(); request.overrideMimeType("application/json"); request.open('GET', 'data.json', true); request.onreadystatechange = function () { if (request.readyState === 4 && request.status ===200) { callback(request.responseText); } }; request.send(null); }
【问题讨论】:
-
我能给你举个像这样的正确例子吗?
-
抱歉没找到你
-
可以在data.json的成功回调中调用names.json的get函数。这将为您解决问题
-
How do I return the response from an asynchronous call? 这是同样的问题,您需要异步任务的结果才能继续执行您的代码
标签: javascript json html