javascript - 如何限制从 API 接收的数据?

标签 javascript json ajax

我正在学习 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

(来自 https://github.com/typicode/jsonplaceholder/issues/65)-

关于javascript - 如何限制从 API 接收的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62609493/

相关文章:

javascript - JavaScript 中的简单 throttle

javascript - Node.js 的路由问题 - 无法 GET

javascript - 使用现有的 json 结构在 javascript 中构建 json 格式

javascript - 如何将动态表转换为jquery数据表?

ajax - 过度依赖ajax

jquery - MVC ajax 返回字符串作为 [object] 对象

javascript - 如何在Jquery中的两个事件函数之间传递变量?

javascript - 如果他们得到某个字符串,我该如何重定向用户

json - Elasticsearch多个术语可以促进

javascript - jQuery 的 $.引用?