我正在玩承諾和API調用,這次是https://www.warcraftlogs.com/v1/docs。這個例子的目標是,當你點擊zones
按鈕時,所有區域都會顯示出來,並允許你點擊它們(該部分完成)。下一部分是在區域對象clicked
(本例中爲encounters
數組)時顯示有關特定區域的詳細信息。訪問該特定JSON對象的JSON子對象
這裏是有問題的筆:http://codepen.io/kresimircoko/pen/ZLJjVM?editors=0011。
問題是如何訪問用戶點擊過的zone
的encounters
數組?
,代碼:
const API_KEY = '?api_key=625023d7336dd01a98098c0b68daab7e';
const root = 'https://www.warcraftlogs.com:443/v1/';
const zonesBtn = document.querySelector('#zones');
const responseList = document.querySelector('#response');
console.clear();
const requestJSON = objType => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
try {
resolve(JSON.parse(this.responseText));
}
catch (e) {
reject(e);
}
};
xhr.onerror = reject;
xhr.open('GET', root + objType + API_KEY);
xhr.send();
});
};
function displayBosses(zoneID) {
requestJSON('zones')
.then(data => {
return data.find(zone => {
return zone.id === zoneID;
});
})
}
function displayZones() {
let output = '';
requestJSON('zones')
.then(zones => {
return zones.map(zone => {
output += `<li data-zoneid="${zone.id}"> ${zone.name} </li>`;
response.innerHTML = output;
}).join('');
})
.then(responseList.style.display = 'flex');
}
zonesBtn.addEventListener('click', displayZones);
responseList.addEventListener('click', evt => {
const zoneID = evt.target.dataset.zoneid;
displayBosses(zoneID);
})
這裏的JSON輸出我工作的一部分:
[
{
"id": 3,
"name": "Challenge Modes",
"frozen": true,
"encounters": [
{
"id": 11182,
"name": "Auchindoun"
},
{
"id": 11175,
"name": "Bloodmaul Slag Mines"
},
{
"id": 11279,
"name": "The Everbloom"
},
{
"id": 11208,
"name": "Grimrail Depot"
},
{
"id": 11195,
"name": "Iron Docks"
},
{
"id": 11176,
"name": "Shadowmoon Burial Grounds"
},
{
"id": 11209,
"name": "Skyreach"
},
{
"id": 11358,
"name": "Upper Blackrock Spire"
}
],
"brackets": [
{
"id": 1,
"name": "6.0"
},
{
"id": 2,
"name": "6.1"
},
{
"id": 3,
"name": "6.2"
}
]
},
{
"id": 4,
"name": "Throne of Thunder",
"frozen": true,
"encounters": [
{
"id": 1577,
"name": "Jin'rokh the Breaker"
},
{
"id": 1575,
"name": "Horridon"
},
{
"id": 1570,
"name": "Council of Elders"
},
{
"id": 1565,
"name": "Tortos"
},
{
"id": 1578,
"name": "Megaera"
},
{
"id": 1573,
"name": "Ji-kun"
},
{
"id": 1572,
"name": "Durumu the Forgotten"
},
{
"id": 1574,
"name": "Primordius"
},
{
"id": 1576,
"name": "Dark Animus"
},
{
"id": 1559,
"name": "Iron Qon"
},
{
"id": 1560,
"name": "Twin Consorts"
},
{
"id": 1579,
"name": "Lei Shen"
},
{
"id": 1580,
"name": "Ra-den"
}
]
},
你有問題嗎? –
您可以發佈從服務器返回的JSON樣本嗎?在不知道結構的情況下,我們無法建議如何訪問。 –
@VanquishedWombat添加了JSON的一部分,特別是前2個對象 –