Reputation: 55
I am learning AJAX.
I am using vanilla JS
I want to put a limit on the data received through an API eg: 10 objects max.
here is the url:- https://jsonplaceholder.typicode.com/photos
The problem is that when I create a GET request then the data which is fetched is huge approx 5000 objects. I want to use limited data so how I go about that.
this is the javaScript code:
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";
}
};
}
Upvotes: 2
Views: 10962
Reputation: 585
to limit the api response until 6 posts https://jsonplaceholder.typicode.com/posts?_limit=6"
Upvotes: 1
Reputation: 71
depends entirely on the server, you can not limit server response via js.
see mrblewog answer and just use jsonplaceholder.typicode.com/photos?_start=0&_limit=5
jsonplaceholder limit query parameter
Upvotes: 4
Reputation:
Adding my comment as an answer.
Limiting often depends on what the server supports.
Check whether the api request has a limit or a paging parameter: in your case try https://jsonplaceholder.typicode.com/photos?_start=0&_limit=5
(from https://github.com/typicode/jsonplaceholder/issues/65) –
Upvotes: 4