如何使用 JS 和 Ajax 获取 Tumblr 帖子的下一页

问题描述 投票:0回答:1

对于使用 vanilla js 的 React 项目,我正在抓取我的 Tumlbr 博客来检索所有照片帖子并将它们嵌入到我的应用程序上的“博客”页面中。我使用 ajax 来执行此操作,因为 tumblr.js 包不支持浏览器内调用,而我的后端位于 Rails 中。以下是获取我的 tumblr 第 1 页上前 20 篇帖子的工作代码:

export const getPosts = () => {
  return (dispatch) => {
    $.ajax({
      url:"https://api.tumblr.com/v2/blog/somewhatadrift.tumblr.com/posts/photo?...&api_key=...",
      type: "GET",
      context: this,
      success: function(result) {
        let posts = result.response.posts.filter(post => post.type === 'photo');
        dispatch(setPosts(posts));
      }
    });
  }
}

此调用的结果看起来像 enter image description here

Tumlbr API 文档指出,total_posts 是“此请求可用的帖子总数,对于对结果进行分页很有用”,但没有给出如何执行此操作的明确示例。

javascript ajax pagination tumblr
1个回答
0
投票

好的。我会尽力回答。

你需要一些类似的东西。

export const getPosts = () => {
    let limit = 20; // set this to any value you want up to 50. 
    const retrieveMore = function (offset) {
        $.ajax({
            url: `https://api.tumblr.com/v2/blog/somewhatadrift.tumblr.com/posts?limit=${limit}&offset=${offset}`,,
            success(result) {
                let i = 0;
                const totalPosts = result.response.total_posts;
                const postLength = result.response.posts.length;
                while (i < postLength) {
                    // do your magic here
                    dispatch(setPosts(posts)); // not sure if this will rerender using React. Usually I would push this to an array. 
                    i++;
                }
                if (totalPosts >= offset && postLength !== 0) {
                    retrieveMore(offset + limit);
                }
            }
        });
    };
    retrieveMore(0);
};

我会尝试分解其中一些。

let limit = 20

您可以将其设置为 50 以内的任何值(但我们将循环遍历它,直到达到帖子总数)。事实上,如果你将其设置为 20,它就是默认值,你实际上不需要它作为 url 中的参数。

url: `https://api.tumblr.com/v2/blog/somewhatadrift.tumblr.com/posts?limit=${limit}&offset=${offset}`,

我们使用反引号将其转换为模板文字,这样我们就可以在每次循环增量时插入一个动态变量。

然后我们使用

i
创建一个计数器。

i
小于
postLength
时,我们提取我们的帖子(或应用您想要的任何逻辑,然后使用
i
增加
i++

然后我们检查

totalPosts
计数是否大于或等于
offset
,如果不是,则有更多帖子要返回,然后我们再次运行该函数,但增加计数器。
retrieveMore(offset + limit);

第一次运行时,我们在下一次运行时使用

retrieveMore(0)
,计数器将递增,直到我们达到检查帖子总数是否大于偏移量加上限制的条件。那时我们知道没有更多的帖子可供检索。

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.