简体   繁体   中英

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);

})

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> 

You can use jsonp using $.ajax() not by $.getJSON(). and you have to declare your callback method in your javascript code

 $("#btn").click(function(){ $.ajax({ url: "http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=myJsonpCallbackMethod", dataType: "jsonp", success: function( response ) { //console.log( response ); // server response } }); }); function myJsonpCallbackMethod(data){ alert("Hello"); console.log( data ); // server response } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <button id="btn">Click Me</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM