任何人都可以帮我解决以下问题。我有2个JSON文件:多个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); }
我可以给你适当的例子像这样吗? – Noman
抱歉没有让你 – Deb
检查我的答案。 – Noman