繁体   English   中英

未正确循环通过 JSON Object

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM