sammy88888888
sammy88888888

Reputation: 478

JSON paginated response javascript

I have some JSON that looks like this:

{
    "count": 156,
    "next": "http://url.com/api/v1/articles/?page=2",
    "previous": null,
    "results": [
        {
            "article_title": "Article 1",
            "pub_date": "2016-03-11T09:00:29Z"
        },
        {
            "article_title": "Article 2",
            "pub_date": "2016-03-11T09:00:29Z"
        },
        {
            "article_title": "Article 3",
            "pub_date": "2016-03-11T09:18:56Z"
        }
    ]
}

The call that receives this looks like this:

$.getJSON("http://url.com/api/v1/articles/?page=1", function (data) {
    console.log(data.next)
});

I would like make another request using the next link provided, and continue to do this until there are no more pages. Any thoughts on how to achieve this. Thanks!

Upvotes: 2

Views: 87

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

You could wrap it in a function then pass the URL as needed.

function nextPage(url) {
  if (!url) {
    return; // Don't do anything if no URL is given
  }
  $.getJSON(url, function(data) {
    // do stuff with data
    nextPage(data.next);
  });
}

Upvotes: 4

Related Questions