如何在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
相关产品推荐
相关产品推荐

