Reputation: 2081
I'm just starting using AJAX and I wonder if it is possible to specify the amount of objects that should be returned from an AJAX call.
For testing I created a JSON.db file from here.
My code looks like this(using Polymer web-component):
HTML:
<body>
<h1>Object-list</h1>
<template is="dom-bind">
<evo-object_list>
</evo-object_list>
</template>
<h1 id = 'loadInHere'></h1>
<button onclick = 'loadDoc()'>Load</button>
<script>
function loadDoc(){
var element = document.querySelector('evo-object_list');
element.loadDoc();
}
</script>
</body>
web-component
loadDoc: function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("loadInHere").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "db.json", true);
xhttp.send();
},
JSON
{
"fathers" : [
{
"id" : 0,
"married" : false,
"name" : "Ronald Taylor",
"sons" : null,
"daughters" : [
{
"age" : 9,
"name" : "Barbara"
}
]
},
{
"id" : 1,
"married" : false,
"name" : "Kevin Lopez",
"sons" : null,
"daughters" : [
{
"age" : 6,
"name" : "Angela"
}
]
},
{
"id" : 2,
"married" : true,
"name" : "Matthew Harris",
"sons" : null,
"daughters" : [
{
"age" : 19,
"name" : "Helen"
}
]
},
{
"id" : 3,
"married" : true,
"name" : "Thomas Lewis",
"sons" : null,
"daughters" : [
{
"age" : 16,
"name" : "Michelle"
},
{
"age" : 8,
"name" : "Dorothy"
}
]
},
{
"id" : 4,
"married" : true,
"name" : "John Martin",
"sons" : null,
"daughters" : [
]
}
]
}
etc.....
My file could be very long and I don't want to load the whole thing, is it possible to define which objects inside the file and how much should be returned. e.g only the first three fathers and then the next three after reclicking the button?
I just use JSON now for testing but could have other files which i don't know now.
Please provide only pure javascript answers I don't want to use jQuery
Upvotes: 1
Views: 248
Reputation: 960
As others said, this is mostly a feature that should be implemented on the server side, but to provide you some guidance the idea is to send a parameter from the JS side, for example:
// Note the limit parameter sent to the server
xhttp.open("GET", "db.json?limit=5", true);
// Note the page parameter sent to the server
xhttp.open("GET", "db.json?page=1", true);
// You can even set custom paginations!
xhttp.open("GET", "db.json?page=5&per_page=50", true);
An example of this implementation is the stack overflow questions list, note the parameters in the URL
https://stackoverflow.com/questions?page=2&sort=newest
Upvotes: 1