【问题标题】:Get all posts from a Tumblr blog using jQuery getJson使用 jQuery getJson 从 Tumblr 博客中获取所有帖子
【发布时间】:2014-07-22 21:36:38
【问题描述】:

我想使用 Tumblr 的 API 使用 jQuery getJson 获取 Tumblr 博客的所有文本帖子。

我尝试使用以下代码,但我只收到了 20 个帖子:

function loadPosts () {

  var key = "api_key=xBcVPLfdDKpH0GjMCd1whW7rPoYkzLgZD3ZwpzndISFI4huSpA"
  var api = "https://api.tumblr.com/v2/blog/only-text-posts.tumblr.com/"
  var post_amount

  $.getJSON(api + "info?" + key,function(data) {
    post_amount = data.response.blog.posts
    $.getJSON(api + "posts/text?&filter=text&limit=" + post_amount + "&" + key,function(data) {
      $.each(data.response.posts, function(i, item) {
        var content = item.body
        $("#Posts ul").append('<li>' + content + '</li>')
      });
    })
  })

}

这是一个很好的 Tumblr 博客示例,用于测试:

http://only-text-posts.tumblr.com/

【问题讨论】:

  • 请添加您的代码并阅读stackoverflow.com/help/how-to-ask
  • @jgillich 抱歉,这是我在 StackOverflow 上的第一个问题。我现在对规则很清楚了,非常感谢。
  • 只是想说,如果您在主题中执行此操作,则可以在主题本身中排除您不想显示/输出的其他帖子类型(文本帖子除外) .不过我不确定你的最终游戏是什么..

标签: javascript jquery ajax tumblr getjson


【解决方案1】:

根据documentation,最多只能返回20个帖子。您可以使用offset 参数指定偏移量,并通过多次调用检索所有帖子:

function loadPosts () {

    var key = "api_key=your_key";
    var api = "https://api.tumblr.com/v2/blog/only-text-posts.tumblr.com/";
    var retrieve_more = function (offset) {
        $.getJSON(api + "posts/text?callback=?&filter=text&limit=20&offset=" + offset + "&" + key,function(data) {
            $.each(data.response.posts, function(i, item) {
                var content = item.body;
                $("#Posts ul").append('<li>' + content + '</li>')
            });

            if (data.response.posts.length == 20) {
                retrieve_more(offset + 20);
            }
        });
    };

    retrieve_more(0);
}

loadPosts();

fiddle

【讨论】:

    【解决方案2】:

    Tumblr Api documentation 开始,每个请求的帖子限制为 20 个。您可以执行多个请求并增加偏移量。

    var max_posts_per_page = 20;
    $.getJSON(api + "info?" + key,function(data) {
        post_amount = data.response.blog.posts;
        for (var offset = 0; offset < post_amount; offset += max_posts_per_page) {
            $.getJSON(api + "posts/text?&filter=text&limit=" + max_posts_per_page + "&offset=" + offset + "&" + key,function(data) {
                $.each(data.response.posts, function(i, item) {
                    var content = item.body
                    $("#Posts ul").append('<li>' + content + '</li>')
                });
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多