You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Axios代码中用forEach循环拉取JSON API的全部数据

遍历JSON API全部数据的修改方案

你的代码通过固定索引[1]只获取了单条数据,要遍历API返回的全部20行数据,只需修改showOutput函数,使用forEach循环遍历res.data.data数组即可,具体修改如下:

修改后的完整代码

function getTodos() {
    axios
        .get('https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v1/accounting/od/rates_of_exchange?fields=country_currency_desc,exchange_rate,record_date&filter=country_currency_desc:in:(Canada-Dollar),record_date:gte:2020-01-20', {
            country_currency_desc: 'Currency',
            exchange_rate: 'last price',
            record_date: 'date',
        })
        .then((res) => showOutput(res))
        .catch((err) => console.log(err))
}

function showOutput(res) {
    // 先拼接表头
    let html = `
        <tr>
            <th>日期</th>
            <th>货币</th>
            <th>汇率</th>
        </tr>
    `;
    // 遍历所有数据行
    res.data.data.forEach(item => {
        html += `
            <tr>
                <td>${item.record_date}</td>
                <td>${item.country_currency_desc}</td>
                <td>${item.exchange_rate}</td>
            </tr>
        `;
    });
    // 将拼接好的HTML插入到页面中
    document.getElementById('row').innerHTML = html;
}

关键修改说明

  • 移除固定索引[1],改用forEach循环遍历res.data.data数组的每一项,实现全量数据获取
  • 新增表头行,让界面结构更清晰规范
  • 把原代码中数据行的<th>替换为<td>(<th>是表头专用单元格,数据行应使用<td>)
  • 去掉不必要的JSON.stringify,API返回的字段可直接渲染使用

内容的提问来源于stack exchange,提问作者Tev1903

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:50:45