hb8 hb8 - 3 months ago 10
JSON Question

retrieving data from jsonp api that contains pages

I'm a little stuck on how I can retrieve all data from a jsonp api when the data is split in pages. The callback looks like this:

{
entries: [],
page: 1,
pages: 101,
posts: 10054
}


the code under only gets me results from page 1, but I would like to get results from all 101 pages. If I add a query to the url like :
&page=2
or
&page=3
I can access objects from that page only, what I'm trying to is access all objects from all pages in one go....
would appreciate some help :)

$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?', function(data){

var html = "";

$.each(data.entries, function(key,value){
html += '<p>' + value.navn + '</p>';
})

$('#test').html(html);

})

VJI VJI
Answer

You can make first call to get the number of pages and in next calls you can loop through them. Try below code

$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?', function(data) {
  var pages = data.pages;
  for (var i = 1; i <= data.pages; i++) {
    $.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?&page=' + i, function(data) {

      $('#test').append("Page " + data.page + " Data >> ");

      var html = "";
      $.each(data.entries, function(key, value) {
        html += '<p>' + value.navn + '</p>';
      })
      $('#test').append(html);
    });
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>

Comments