Reputation: 265
I have been trying to create a webpage that appends JSON data into a ul
. The problem is that the JSON file has more than 600 values.
I would like to limit the number of values retrieved, say 10 and then add a 'load more' button to append more, eg. 10 more, to it and so on. Here's my code.
<body onload="loadUser(20)">
<ul id="placeholder"></ul>
function loadUser(arg) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'people.json', true);
xhr.onload = function() {
if (this.status == 200) {
var users = JSON.parse(this.responseText);
for (var i = 0; i < arg; i++) {
var output = `<li class="list_item">${users[i].name</li>`;
document.getElementById('placeholder').innerHTML += output;
}
document.getElementById('placeholder').innerHTML += '<button onclick="loadmore()">load more</button>';
}
}
xhr.send();
}
// JSON Example:
[{
"id": 1,
"name": "Mithu Mondal",
"email": "[email protected]"
},
{
"id": 2,
"name": "Frankenstien",
"email": "[email protected]"
}
]
Here's the link: https://www.mithuation.ml/jsonExample/
Thanks in Advance.
Upvotes: 0
Views: 2185
Reputation: 69
I guess this is what you are searching for Lazy.js. It will parse as much of the JSON as possible, asynchronously.
Import the libraries:
<script type="text/javascript" src="lazy.js"></script>
<!-- optional: if you want support for DOM event and AJAX-based sequences: -->
<script type="text/javascript" src="lazy.browser.js"></script>
If your want to retrieve 10 item at a time:
var response = JSON.parse(this.responseText);
var result = Lazy(response)
.take(10);
document.getElementById('placeholder').innerHTML += output;
Upvotes: 1
Reputation: 6550
When you perform an AJAX
request (XMLHTTPRequest
) it loads the entire file. There is no way to have the browser load a partial file.
If you do not plan to use a database (which would allow you to query a certain number of items at a time), I recommend that you split your data up into several JSON
files. When you perform the XMLHTTPRequest
, you will only retrieve a subset of the data. For the next request, you will retrieve the next file and thus get the next set of data.
Upvotes: 1