无法正确遍历CoinRankingAPI返回的JSON对象问题求助
问题解决:CoinRankingAPI遍历币种价格时的“不可迭代对象”错误
核心错误原因
- URL参数构造错误:你的API密钥没有以正确的参数名传递,CoinRankingAPI要求密钥通过
api_key查询参数传递,原代码直接拼接密钥会导致请求无效或响应结构异常。 - 响应结构解析错误:API返回的
data是一个对象,而非可迭代数组,真正的币种列表在data.coins字段中,直接遍历data会触发“不可迭代”错误。
修正后的代码
const apiKey = 'XXXX'; const url = `https://api.coinranking.com/v2/coins?api_key=${apiKey}`; function loadPrices() { // 用fetch替代XMLHttpRequest,代码更简洁 fetch(url) .then(response => response.json()) .then(result => { // 正确获取可迭代的币种数组 const coinsList = result.data.coins; const container = document.getElementById("hello"); // 先拼接所有内容再一次性插入DOM,提升性能 let priceHtml = ''; coinsList.forEach(coin => { priceHtml += `<br />${coin.price}`; }); container.innerHTML = priceHtml; }) .catch(error => { console.error('请求出错:', error); }); } // 调用函数加载数据 loadPrices();
关键修正点说明
- URL修正:使用模板字符串拼接
api_key参数,确保API能正确识别密钥。 - 响应解析修正:从
result.data.coins获取可迭代的币种数组,而非直接使用result.data。 - DOM操作优化:先拼接HTML字符串再一次性赋值给
innerHTML,避免频繁修改DOM造成性能损耗。 - 错误处理:添加
catch块捕获请求或解析过程中的错误,方便调试。
内容的提问来源于stack exchange,提问作者smoo123
相关产品推荐
相关产品推荐

