使用JavaScript编写一个计数器,并将其集成到API调用中,以便获取所有记录。以下是一个简单的示例:
let allRecords = [];
function getRecords(start) {
let url = `https://api.example.com/records?start=${start}`;
fetch(url)
.then(response => response.json())
.then(data => {
allRecords = allRecords.concat(data.records);
if (data.next) {
getRecords(data.next);
} else {
console.log(`All records retrieved: ${allRecords}`);
}
})
.catch(error => console.error(error));
}
getRecords(0);
这个示例使用递归调用来处理所有的记录。它从API检索200条记录,并将它们添加到一个数组中。如果API返回多个页面,它会使用下一页的链接来获取下一页的数据,直到获取所有记录为止。在此示例中,所有记录都存储在allRecords
数组中,并在完成时打印出来。
上一篇:API显示数据问题。