[英]Not looping through JSON Object Correctly
我目前正在嘗試制作自己的加密貨幣監視列表。 我正在使用 CoinRankingAPI( https://developers.coinranking.com/api/documentation/coins )。 我試圖遍歷硬幣數據以檢索價格,但我收到一條錯誤消息,指出我試圖迭代的 object 並不煩躁。 源代碼將在下面。 任何幫助將不勝感激!
const key = 'XXXX'; const url = 'https://api.coinranking.com/v2/coins?' + key; //Loads Stats Data function loadPrices() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var coins = JSON.parse(this.responseText); // get 'data' key inside response var price = coins.data; // loop all the teams for (var coin of price) { // print full name and abbreivation document.getElementById("hello").innerHTML += "<br />" + coin["price"]; } } }; xhttp.open("GET", url, true); xhttp.send(); }
在查看所提供鏈接的預期響應后,它將硬幣作為 object 返回,其中包含data
值,而數據值又包含coins
。 您在如何構建請求和處理事件方面也存在問題。 因此,為了迭代硬幣,請嘗試以下代碼:
xhttp.onreadystatechange = function(e) {
const req = e.target;
if (req.readyState == 4 && req.status == 200) {
const response = JSON.parse(req.response);
// get 'data' key inside response
const coins = response.data.coins;
for (let coin of coins) {
document.getElementById("hello").innerHTML += "<br />" + coin["price"] ;
}
}
}
但同時,您可以使用 fetch API 和async
/ await
來簡化您的代碼。 所以,讓我提供一個更好/優化的代碼版本:
const key = 'XXXX';
const url = 'https://api.coinranking.com/v2/coins?' + key;
//Loads Stats Data
async function loadPrices() {
const response = await fetch(url);
const coins = (await response.json()).data.coins;
const helloElm = document.getElementById("hello");
// loop all the teams
let output = '';
for (var coin of coins) {
// print full name and abbreivation
output += "<br />" + coin["price"] ;
}
helloElm.innerHTML = output;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.