JSON 分页响应 JavaScript

JSON paginated response javascript

本文关键字:JavaScript 响应 分页 JSON      更新时间:2023-09-26

我有一些看起来像这样的JSON:

{
    "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"
        }
    ]
}

接收此消息的调用如下所示:

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

我想使用提供的next链接提出另一个请求,并继续这样做,直到没有更多页面。关于如何实现这一目标的任何想法。谢谢!

您可以将其包装在函数中,然后根据需要传递URL。

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