如何在facebook javascript API中进行分页?

时间:2011-02-17 00:13:56

标签: javascript facebook facebook-graph-api pagination

我正在尝试使用javascript sdk恢复我的facebook新闻Feed中的上周帖子。 我能够获得第一页,但后来,我不知道如何继续迭代其他页面。我用以下代码尝试过它:

 $('#loadPosts').bind('click', function() {     
            FB.api('/me/home',{since:'last week'}, getPosts);   
          });

 getPosts = function(response){
        for (element in response.data){
            post = response.data[element]
            console.log(post);          
          }

          previousPage = response.paging.previous;        
          console.log(previousPage);

          // can i call FB.api(previousPage, getPosts); ??      

      }

但我收到一个URL作为上一页,我不知道如何从该URL进行javascript FB.api调用。有什么想法吗?

5 个答案:

答案 0 :(得分:31)

好吧,对于一个简单的问题我似乎很抱怨,我仍然相信我的旧答案澄清了。无论如何,让我照顾你。 :)

首先:我发现你无法真正从第一页进入“上一页”页面。理想情况下,我应该。所以,这是我提交的您可能想要关注的错误:https://developers.facebook.com/bugs/391562790938294?browse=search_50fcac3ce094e7068176315

第二次:如果这是设计的,你不能从第一页回到“上一页”(因为 之前没有),但你肯定可以去到“下一步”。但是,由于API表现为游标,并且您已向前移动,现在您的“上一页”将起作用。

问题的答案:
我在上一页获得了一个URL,但我不知道如何从该URL进行javascript FB.api调用。有什么想法吗?

  是的,你可以拨打FB.api电话。但我建议你改为进行HTTP GET调用,因为它更容易。另请注意,之前可能会返回并清空{"data":[]}

之类的数组

如何获取上一页/下一页?
在这里,我正在编写一个使用jQuery的小代码。如果您不想阅读代码,有两种方法:

  1. 使用上一个/下一个URL并发出HTTP GET请求。如果不是空的话,它将带有下一组“上一个”,“下一个”链接。
  2. 解析URL,并将查询字符串作为JSON传递给FB.api。我使用jQuery BBQ pluging进行解析。
  3. 重要说明:在示例中,我使用的是“下一个”网址,因为在第一次请求时,如果我使用“上一个”,则会提供空的JSON,而不是过去提供的帖子。但是,一旦我向前移动几页,我就可以使用“之前的”URL。与Google搜索结果一样,您无法在第1页上转到上一页,但您可以从任何页面> 1(参见下面的实施例3)。这称为分页。

    示例1:使用HTTP GET的代码(首选):(我将加载3个帖子/页面并查看3个下一页)

    <html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
    <script type="text/javascript" src="https://raw.github.com/cowboy/jquery-bbq/master/jquery.ba-bbq.min.js"></script>
    <script>
    
    var i =0;
    var getPosts = function (response){
              for (element in response.data){
                post = response.data[element]
                console.log(post.id + ": " +post.message);          
              }
    
    
    
              // can i call FB.api(nextPage, getPosts); ??
              if(i < 2){
                  nextPage = response.paging.next;        
                  console.log(nextPage);
                  i++;
                  //Method 1: I use it.
                  $.get(nextPage, getPosts, "json"); //optional: $.getJSON can be use instead
              }
    
          }
    
    $(document).ready(function(){
    
    $('#loadPosts').bind('click', function() {
                FB.api('/me/home',{since:'yesterday','limit': '3'}, getPosts);   
              });
    })
    </script>
    </head>
    <body>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        // init the FB JS SDK
        FB.init({
          appId      : 'XXXXXXXXXXXX', // FILL YOUR APP ID HERE!
          status     : true, // check the login status upon init?
          cookie     : true, // set sessions cookies to allow your server to access the session?
        });
    
        // Additional initialization code such as adding Event Listeners goes here
    
      };
    </script>
    <button id="loadPosts">Load Posts</button>
    <p>Please open developer console to see what's happening. In Firefox, you can use ctrl+shift+k, and in Chrome/Chromium use ctrl+shift+i</p>
    </body>
    </html>
    

    响应

    100004192352945_156620584487686: undefined
    137723270230_10152423499430231: On this day, please spare a thought for those fellow citizens, for whom I just spare a thought and do nothing else.
    642965867_10151211036740868: Thanks everyone for their wishes! The wishes made my day!
    
    https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD&until=1359184568
    367116489976035_536776529676696: Rage. Quit. Life.
    899605553_10152450871820554: undefined
    367116489976035_417820828298092: undefined
    
    https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD&until=1359179890
    137723270230_10152423148745231: Pratibha Patil used to love the Republic Day Parade, especially the part where the visiting Chief Guest extended her an invitation to visit his/her own country.
    137723270230_10152423131700231: The Kingfisher tableau at Republic Day Parade was so simple. Vijay Mallya riding a bicycle.
    367116489976035_484460034950769: undefined
    

    示例2:使用FB.api的代码:(我将加载3个帖子/页面并查看3个下一页)

    <html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
    <script type="text/javascript" src="https://raw.github.com/cowboy/jquery-bbq/master/jquery.ba-bbq.min.js"></script>
    <script>
    
    var i =0;
    var getPosts = function (response){
              for (element in response.data){
                post = response.data[element]
                console.log(post.id + ": " +post.message);          
              }
    
    
    
              // can i call FB.api(nextPage, getPosts); ??
              if(i < 2){
                  nextPage = response.paging.next;        
                  console.log(nextPage);
                  i++;
    
                  //Method 2: If you have to call FB.api
                  var params = jQuery.deparam.querystring(nextPage);
                  console.log(JSON.stringify(params, null, 2));
                  FB.api('/me/home', params, getPosts)
              }
    
          }
    
    $(document).ready(function(){
    
    $('#loadPosts').bind('click', function() {
                FB.api('/me/home',{since:'yesterday','limit': '3'}, getPosts);   
              });
    })
    </script>
    </head>
    <body>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        // init the FB JS SDK
        FB.init({
          appId      : 'XXXXXXXXXXXX', // FILL YOUR APP ID HERE!
          status     : true, // check the login status upon init?
          cookie     : true, // set sessions cookies to allow your server to access the session?
        });
    
        // Additional initialization code such as adding Event Listeners goes here
    
      };
    </script>
    <button id="loadPosts">Load Posts</button>
    <p>Please open developer console to see what's happening. In Firefox, you can use ctrl+shift+k, and in Chrome/Chromium use ctrl+shift+i</p>
    </body>
    </html>
    

    响应

    367116489976035_536776529676696: Rage. Quit. Life.
    899605553_10152450871820554: undefined
    367116489976035_417820828298092: undefined
    {
      "limit": "3",
      "access_token": "AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD",
      "until": "1359179890"
    }
    
    137723270230_10152423148745231: Pratibha Patil used to love the Republic Day Parade, especially the part where the visiting Chief Guest extended her an invitation to visit his/her own country.
    137723270230_10152423131700231: The Kingfisher tableau at Republic Day Parade was so simple. Vijay Mallya riding a bicycle.
    367116489976035_484460034950769: undefined
    
    https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD&until=1359178140
    {
      "limit": "3",
      "access_token": "AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD",
      "until": "1359178140"
    }
    655515199_403590309726450: a good resolution to take on Republic Day
    505588854_496901583686790: Love the secret world that slow motion reveals.
    693811975_10151217837201976: undefined
    

    示例3:执行:page1 - &gt;第2页 - &gt;第1页或第 - 页 - &gt;下一个 - &gt;上一页以下代码将加载page1,然后转到“下一页”(第2页),然后返回第1页,使用“上一页”

    <html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
    <script type="text/javascript" src="https://raw.github.com/cowboy/jquery-bbq/master/jquery.ba-bbq.min.js"></script>
    <script>
    
    var i =0;
    var getPosts = function (response){
              for (element in response.data){
                post = response.data[element]
                console.log(post.id + ": " +post.message);          
              }
    
    
    
              // can i call FB.api(nextPage, getPosts); ??
              if(i < 2){
                  nextPage = response.paging.next;        
                  if(i==1)
                    nextPage = response.paging.previous;
    
                  console.log(nextPage);
                  i++;
                  $.get(nextPage, getPosts, "json"); //optional: $.getJSON can be use instead
              }
    
          }
    
    $(document).ready(function(){
    
    $('#loadPosts').bind('click', function() {
                FB.api('/me/home',{since:'yesterday','limit': '3'}, getPosts);   
              });
    })
    </script>
    </head>
    <body>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        // init the FB JS SDK
        FB.init({
          appId      : 'XXXXXXXXXXXX', // FILL YOUR APP ID HERE!
          status     : true, // check the login status upon init?
          cookie     : true, // set sessions cookies to allow your server to access the session?
        });
    
        // Additional initialization code such as adding Event Listeners goes here
    
      };
    </script>
    <button id="loadPosts">Load Posts</button>
    <p>Please open developer console to see what's happening. In Firefox, you can use ctrl+shift+k, and in Chrome/Chromium use ctrl+shift+i</p>
    </body>
    </html>
    

    响应

    PAGE1:
    367116489976035_536806916340324: How big is the Solar System?
    Full infographic here: http://bit.ly/WmzfVn
    137723270230_10152423534790231: "Sociologist" Ashis Nandy has claimed that most of the corrupt came from OBC/SC/ST castes.
    Following this, Corrupt people have strongly condemned Nandy's attempts to divide them on caste lines. They'll be united in loot, forever.
    100004192352945_156620584487686: undefined
    
    PAGE2:
    https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAKqIMyCVYjH9upK4e2bjUwLoVbbFDL0ffc0SZBTVR9MUFGV4ZCq6HBdFIadFMpLDC3ATMZCJ4GPsXWpG4qTGODavuvzLAZDZD&until=1359185659
    
    137723270230_10152423499430231: On this day, please spare a thought for those fellow citizens, for whom I just spare a thought and do nothing else.
    642965867_10151211036740868: Thanks everyone for their wishes! The wishes made my day!
    367116489976035_536776529676696: Rage. Quit. Life.
    
    PAGE1:
    https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAKqIMyCVYjH9upK4e2bjUwLoVbbFDL0ffc0SZBTVR9MUFGV4ZCq6HBdFIadFMpLDC3ATMZCJ4GPsXWpG4qTGODavuvzLAZDZD&since=1359185123&__previous=1
    
    367116489976035_536806916340324: How big is the Solar System?
    Full infographic here: http://bit.ly/WmzfVn
    137723270230_10152423534790231: "Sociologist" Ashis Nandy has claimed that most of the corrupt came from OBC/SC/ST castes.
    Following this, Corrupt people have strongly condemned Nandy's attempts to divide them on caste lines. They'll be united in loot, forever.
    100004192352945_156620584487686: undefined
    

    OLD ANSWER

    使用limitoffsetsinceuntil参数来实现您的目标。

    参考:http://developers.facebook.com/docs/reference/api/

      

    <强>寻呼

         

    查询连接时,有几个有用的参数可用于过滤和翻页连接数据:

         

    以下内容应该从last week收到yesterday之后的所有帖子21st - 30th消息(基本上,每页10封邮件的第三页分页)。

     FB.api(
      '/me/home',
      {
        'since':'last week',
        'limit': '10',
        'offset': '20',
        'until': 'yesterday'
      }, 
      getPosts
    ); 
    

    我刚刚测试过,它有效。我使用limit = 4,这是页面大小的东西。因此,当我从2011年2月2日(Unix时间戳:1296626400)获取数据到今天使用此

    https://graph.facebook.com/me/home?access_token=[AUTH_TOKEN]&since=1296626400&limit=4
    

    它返回数据,并且还返回URL以转到下一页

    {
       "data": [
          <ARRAY OF POSTS HERE>
       ],
       "paging": {
          "previous": "https://graph.facebook.com/me/home?access_token=[NEW_AUTH_TOKEN]&since=1298026753&limit=4",
          "next": "https://graph.facebook.com/me/home?access_token=[NEW_AUTH_TOKEN]&limit=4&until=1298023222"
       }
    }
    

    您可以安全地使用JSON对象的previousnext属性跳转到下一页(或上一页)。这似乎是最简单的方法。

    顺便说一下,\u00257C需要转换为|才能使其发挥作用。

答案 1 :(得分:7)

如果您只是想获取下一页(使用paging.next对象),您可以执行jQuery.getJSON请求。如下所示:

function loadAlbums(){
    FB.api('/me/albums', function(response){
        handleAlbumsResponse(response);
    });
}

function handleAlbumsResponse(response){
    var albums = response.data;

    for( var i in albums){
        var album = albums[i];
        $('#albums ul').append('<li><a href="#">' + album.name + '</a></li>');
    }

    if( response.paging.next){
        console.log('fetching next page...');
        $.getJSON(response.paging.next, function(response){                
            handleAlbumsResponse(response);
        });
    } 
} 

答案 2 :(得分:3)

您问题中的关键约束是我们无法使用响应中提供的“下一个”网址。

我会首先回答一个更为笼统的问题,试着回答你的问题:

  

我们如何为我们的Facebook应用创建用户体验,其中每次调用更多商品都会返回相同数量的商品。

如果用户请求'more'并获得10个项目,请按'more'然后获得4,然后7等,她可能会认为我们的应用程序有问题。

在Open Graph intro page上,引入了不同的分页参数。这些是:

  

限制

     

偏移

     

,直到

     

因为

如'paging'标题下所述。但是,如果我们实现一个带限制和偏移的解决方案,我们增加偏移量,例如:

https://graph.facebook.com/me/home?limit=10&offset=OFFSET

其中OFFSET将增加每个请求的限制,我们发现返回的结果数有时不等于我们指定的“limit”参数。这是因为在检查查询结果是否对查看者可见之前,参数将应用于Facebook的侧。我们要求10,但我们可能会收到8件物品。

这意味着如果我们希望我们的应用“更多”请求始终返回相同数量的项目,我们就无法使用我们增加限制和抵消的解决方案。

Jeff Bowen(在Facebook平台团队工作)在此blog中提出的解决方案就是这样的逻辑:

  • 请求项目,限制= YOUR_LIMIT。
  • 检索响应中最后一项的created_time字段。
  • 请求以下10件商品,因为= RETRIEVED_CREATED_TIME并且限制= YOUR_LIMIT

这是一个代码示例,基于上面提到的博客文章中的示例:

var graphURL = "https://graph.facebook.com/me/home?" +
                 "callback=processResult&" +
                 "date_format=U&" +
                 "limit=10";

function loadPosts() {
  var script = document.createElement("script");
  script.src = graphURL;
  document.body.appendChild(script);
}

function processResult(posts) {
  if (posts.data.length == 0) {
    document.getElementById("loadMore").innerHTML =
      "No more results";
  }
  else {
    graphURL = graphURL + "&until=" +
      posts.data[posts.data.length-1].created_time;

    for (var post in posts.data) {
      var message = document.createElement("div");
      message.innerHTML = posts.data[post].message;
      document.getElementById("content").appendChild(message);
    }
  }
}

此解决方案按时间顺序从用户的新闻源中检索接下来的10个项目,而不使用JSON响应中的URL。

答案 3 :(得分:0)

它正在运作

    function friends_list()
    {

        for (var x = 0; x<500; x++)
        {
            FB.api(
            '/me/friendlists/',
            'GET',
            {"fields":"id","offset":x},
            function(response) {
            for (i = 0; i < response.data.length; i++) 
            { 

            document.getElementById("friends_list").innerHTML =  
            document.getElementById("friends_list").innerHTML + "<br>" + response.data[i].id; 

            }
            document.getElementById("friends_list").innerHTML =  
            document.getElementById("friends_list").innerHTML + "<br>" ;
            }
            );
        }


    }

答案 4 :(得分:0)

我注意到问题很严重。这些天我的回答是正确的FB jsSDK(2017):)

实际上它比前面描述的更简单并且有点直观。 FB jsSDK它本身就是一个API,它可以通过自身和使用相同的方式浏览响应的页面,不是吗?

function getPosts(){
    FB.api('/me/posts', 'GET', {limit:250}, cbGetPosts);
}

function cbGetPosts(response){
    // do your stuff with response.data
    if(response && response.paging){
     FB.api(response.paging.next, cbGetPosts); // yep, is this simple
    }
}

显然,只要定义了下一个键,但是这将要求下一页,但是证明了这个概念。