我正在学习 AJAX。
我正在使用原生 JS
我想限制通过 API 接收的数据,例如:最多 10 个对象。
这是网址:- https://jsonplaceholder.typicode.com/photos
问题是,当我创建 GET 请求时,获取的数据非常庞大,大约有 5000 个对象。我想使用有限的数据,所以我该怎么做。
这是 javaScript 代码:
const next = document.getElementsByTagName("button"),
body = document.querySelector("body");
body.addEventListener("DOMContentLoaded",runEvents);
function runEvents(){
nextBtn();
}
function nextBtn(){
//set up the XMLHTTPObject ajax object
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/photos", true);
xhr.onprogress = function(){
document.getElementsByTagName("img").setAttribute("src", "img/loading.gif");
};
xhr.onload = function(){
if(this.status === 200){
document.getElementsByTagName("p").textContent = "Data Found"
//I want to use the data recieved here
}else{
document.getElementsByTagName("img").style.display = "none";
document.getElementsByTagName("p").textContent = "Data not found";
}
};
}
最佳答案
添加我的评论作为答案。
限制通常取决于服务器支持什么。
检查 api 请求是否有限制或分页参数:在你的情况下尝试 https://jsonplaceholder.typicode.com/photos?_start=0&_limit=5
关于javascript - 如何限制从 API 接收的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62609493/