通过javascript和FB.api下载facebook帖子时如何进行分页?

时间:2014-12-05 20:15:56

标签: javascript facebook-graph-api for-loop

我想通过javascript SDK下载facebook墙贴。我设法拨打前25个帖子,但是当我试图获取paging.next并使用循环将其提供给新的调用时,我遇到麻烦,然后迭代它直到没有更多的页面可用。< / p>

代码生成相同的页面10次,我不明白。它应该给出下一页和下一页以及下一页..?

FB.login(function(response){

        // FIRST CALL THAT CALLS FOR PAGENAME/FEED
        FB.api(request, function (response) {

            // PRINTS TO LOG AND DECLARES X AS THE NEXT PAGE
            console.log(response.paging.next);
            var x = response.paging.next;

            // LOOP THAT PREFERABLY SHOULD CONTINUE UNTIL NO MORE PAGES
            // BUT I WILL DEAL WITH THAT LATER
            for (i = 0; i < 10; i++) {

                // CALLS X WHICH ALSO GIVES ME RHE NEXT PAGE
                // BUT FOR SOME REASON THE CODE DOES NOT MANAGE TO CHANGE
                // X AND DO A NEW CALL
                FB.api(x, function (res){

                    console.log(i);
                    console.log(res.paging.next);
                    // HERE I RESPECIFY X
                    x = res.paging.next;

                    });

                };

           }

          ); 

    }, {scope: 'publish_actions'});

1 个答案:

答案 0 :(得分:5)

您需要学习如何处理异步JavaScript以及如何执行递归函数。您正在尝试在异步API调用设置之前使用“x”。意思是,整个for循环在“x”甚至设置一次之前完成 - 因为API调用需要一段时间。

这是一些快速代码,没有测试它,但它应该显示一个解决方案:

var items = [];
function apiCall(next) {
    FB.api(next, function (response) {
        for (var i = 0; i < response.data.length; i++) {
            //add all posts to the items array
            items.push(response.data[i]);
        }
        if (response.paging && response.paging.next) {
            //call function recursively until there is no "next"
            apiCall(response.paging.next);
        } else {
            //this is when it´s done
            console.log(items);
        }
    });
}
apiCall('/page-id/feed');

确保您了解这些概念,了解何时处理JavaScript SDK和JavaScript非常重要。