任何人都可以幫我解決以下問題。我有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