facebook javascript API 中的分页如何工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5023757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does paging in facebook javascript API work?
提问by Fgblanch
I'm trying to recover the last week posts in my facebook news feed with the javascript sdk. I'm able to get the first page but then, I don't know how to continue iterating through the other pages. I've tried it with the following code:
我正在尝试使用 javascript sdk 在我的 facebook 新闻提要中恢复上周的帖子。我能够获得第一页,但是,我不知道如何继续遍历其他页面。我用下面的代码试过了:
$('#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); ??
}
But I'm getting a URL as previous page and I don't know how to make a javascript FB.api call from that URL. Any ideas?
但是我得到一个 URL 作为上一页,我不知道如何从该 URL 进行 javascript FB.api 调用。有任何想法吗?
回答by Nishant
Alright, it seems a lot of whining about a simple issue that I still believe my old answer clarifies. Anyway, let me babysit you. :)
好吧,似乎有很多关于一个简单问题的抱怨,我仍然相信我的旧答案澄清了。无论如何,让我照顾你。:)
First: I find out that you cannot really go to the "previous" page from the first page. Ideally, I should. So, here is a bug that I have filed you may want to follow: https://developers.facebook.com/bugs/391562790938294?browse=search_50fcac3ce094e7068176315
第一:我发现您无法从第一页真正转到“上一个”页面。理想情况下,我应该。所以,这是我提交的一个错误,你可能想要关注:https: //developers.facebook.com/bugs/391562790938294?browse=search_50fcac3ce094e7068176315
Second: If this is by design, you cannot go back to "previous" from the first page (because there isno previous), but you can surely go to "Next". However, since the API behaves as a cursor, and you have moved forward, now your "previous" page would work.
第二:如果这是由设计,你不能从第一页就又回到“以前”(因为是以前没有),但是你一定能够进入“下一步”。但是,由于 API 表现为游标,并且您已经向前移动,现在您的“上一个”页面可以工作了。
The answer to the question:
I'm getting a URL as previous page and I don't know how to make a javascript FB.api call from that URL. Any ideas?
问题的答案:
我得到一个 URL 作为上一页,但我不知道如何从该 URL 进行 javascript FB.api 调用。有任何想法吗?
yes, you can make FB.api call. But I suggest you to make a HTTP GET call instead, because it's easier. Also, note that previous may return and empty array like
{"data":[]}
是的,您可以进行 FB.api 调用。但我建议您改为进行 HTTP GET 调用,因为它更容易。另外,请注意,前一个可能会返回和空数组,如
{"data":[]}
How to get previous/next page?
Here, I am writing a small code that uses jQuery. In case you do not want to read the code, there are two ways:
如何获取上一页/下一页?
在这里,我正在编写一个使用 jQuery 的小代码。如果您不想阅读代码,有两种方法:
- Use previous/next URL and make HTTP GET request. Which, if not empty, will come with next set of "previous", "next" link.
- Parse the URL, and get the query-string as JSON ans pass it to
FB.api
. I used jQuery BBQ plugingfor parsing.
- 使用上一个/下一个 URL 并发出 HTTP GET 请求。其中,如果不为空,将带有下一组“上一个”、“下一个”链接。
- 解析 URL,并以 JSON 的形式获取查询字符串并将其传递给
FB.api
. 我使用jQuery BBQ 插件进行解析。
Important Note:In the example, I am using "next" URL because on the first request if I use "previous" it gives empty JSON instead of giving posts from the past. However, I can use use "previous" URL once I have moved ahead a few pages. Like Google results, you can not go previous on page 1, but you can from any page > 1 (see Example 3 below). This is called pagination.
重要说明:在示例中,我使用“下一个”URL,因为在第一个请求中,如果我使用“上一个”,它会给出空的 JSON,而不是给出过去的帖子。但是,一旦我向前移动了几页,我就可以使用“上一个”URL。与 Google 结果一样,您不能在第 1 页上转到上一页,但可以从任何 > 1 页(请参见下面的示例 3)。这称为分页。
Example 1: Code using HTTP GET (preferred):(I will load 3 posts/page and look three next-pages)
示例 1:使用 HTTP GET 的代码(首选):(我将加载 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>
Response:
回应:
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
Example 2: Code using FB.api:(I will load 3 posts/page and look three next-pages)
示例 2:使用 FB.api 的代码:(我将加载 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>
Response:
回应:
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
Example 3: Performing: page1 -> page2 -> page1 or page -> next -> previousThe following code will load page1, then go to "next" page (page2), then come back to page1, using "previous"
示例3:执行:page1 -> page2 -> page1 or page -> next -> previous下面的代码将加载page1,然后转到“next”页面(page2),然后回到page1,使用“previous”
<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>
Response:
回应:
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
旧答案
Use limit
, offset
, since
and until
parameters to achieve your goal.
使用limit
,offset
,since
和until
参数,以实现自己的目标。
Refer: http://developers.facebook.com/docs/reference/api/
参考:http: //developers.facebook.com/docs/reference/api/
Paging
When querying connections, there are several useful parameters that enable you to filter and page through connection data:
- limit, offset: https://graph.facebook.com/me/likes?limit=3
- until, since (a unix timestamp or any date accepted by strtotime): https://graph.facebook.com/search?until=yesterday&q=orange
分页
查询连接时,有几个有用的参数可让您过滤和分页连接数据:
The following should get all the posts since last week
until yesterday
from 21st - 30th
message (basically, third page of 10 message per page pagination).
以下应该获得所有帖子,last week
直到yesterday
从21st - 30th
消息开始(基本上,每页分页 10 条消息的第三页)。
FB.api(
'/me/home',
{
'since':'last week',
'limit': '10',
'offset': '20',
'until': 'yesterday'
},
getPosts
);
I've just tested, it works. I have used limit=4, which is page-size kind of thing. So, when I fetch data since Feb 02, 2011 (Unix Time Stamp: 1296626400) till today using this
我刚刚测试过,它有效。我使用了 limit=4,这是页面大小的东西。因此,当我从 2011 年 2 月 2 日(Unix 时间戳:1296626400)到今天使用它获取数据时
https://graph.facebook.com/me/home?access_token=[AUTH_TOKEN]&since=1296626400&limit=4
It returns the data, plus it also return URL to go to next page
它返回数据,另外它还返回 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"
}
}
You can safely use previous
and next
attributes of the JSON object to jump to next page (or previous page). This seems to be the easiest way to do.
您可以安全地使用JSON 对象的previous
和next
属性跳转到下一页(或上一页)。这似乎是最简单的方法。
By the way, \u00257C
needed to be converted to |
to get this to work.
顺便说一句,\u00257C
需要转换为|
使其工作。
回答by Craig Myles
If you simply wanted to get the next page (using the paging.next object) you could do a jQuery.getJSON request. Something like the following:
如果您只是想获取下一页(使用 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);
});
}
}
回答by Gunnar Karlsson
The key constraint in your question is we can't use the 'next' url provided in the response.
您问题中的关键限制是我们不能使用响应中提供的“下一个”网址。
I'll try to answer your question by first asking a more general question:
我将尝试通过首先提出一个更一般的问题来回答您的问题:
How can we create a user experience for our Facebook app where every call for more items returns the same amount of items.
我们如何为我们的 Facebook 应用创造一种用户体验,让每次调用更多项目返回相同数量的项目。
If the user requests 'more' and gets 10 items, presses 'more' and gets then 4, then 7 etc, she might think our app is buggy.
如果用户请求“更多”并获得 10 个项目,按“更多”并获得 4、7 等,她可能认为我们的应用程序有问题。
On the Open Graph intro page, different parameters for paging are introduced. These are:
在 Open Graph介绍页面上,介绍了用于分页的不同参数。这些是:
limit
offset
until
since
限制
抵消
直到
自从
as mentioned under the 'paging' heading. However if we implement a solution with limit and offset where we increment offset ,e.g.:
如“分页”标题下所述。但是,如果我们实现了一个带有限制和偏移的解决方案,我们增加了 offset ,例如:
https://graph.facebook.com/me/home?limit=10&offset=OFFSET
where OFFSET will be increased by the limit each request, we find that the number of results returned will sometimes not be equal to the “limit” parameter we specified. This is because parameters are applied on Facebook's side beforechecking if the queried results are visible to the viewer. We ask for 10, but we might get 8 items in return.
其中 OFFSET 会增加每个请求的限制,我们发现返回的结果数量有时会不等于我们指定的“限制”参数。这是因为在检查查询结果是否对查看者可见之前,参数已应用于 Facebook 端。我们要求 10 件,但我们可能会得到 8 件作为回报。
This means we can't use a solution where we increment limit and offset if we want our app's 'more' request to always return the same amount of items.
这意味着如果我们希望我们的应用程序的“更多”请求始终返回相同数量的项目,我们就不能使用增加限制和偏移量的解决方案。
A solution proposed in this blogby Jeff Bowen (who works on the Facebook plaform team) is this logic:
Jeff Bowen(在 Facebook 平台团队工作)在这篇博客中提出的解决方案是这样的逻辑:
- request item with limit = YOUR_LIMIT.
- retrieve the created_time field of the last item in the response.
- request next 10 items with since = RETRIEVED_CREATED_TIME and limit=YOUR_LIMIT
- 请求项目的限制 = YOUR_LIMIT。
- 检索响应中最后一项的 created_time 字段。
- 请求接下来的 10 个项目,因为 = RETRIEVED_CREATED_TIME 和 limit=YOUR_LIMIT
Here's a code sample, based on an example in the blog post mentioned above:
这是一个代码示例,基于上述博客文章中的示例:
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);
}
}
}
This solution retrieves the next 10 items from the user's newsfeed in chronological order without using the url in the JSON response.
此解决方案按时间顺序从用户的新闻源中检索接下来的 10 个项目,而不使用 JSON 响应中的 url。
回答by Googlian
It's working
它正在工作
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>" ;
}
);
}
}
回答by bluehipy
I noticed the question is very old. My answer is true for the these days FB jsSDK (2017) :)
我注意到这个问题很老了。这几天我的回答是真实的 FB jsSDK (2017) :)
Actually it's simpler than what predecessors described and somewhat intuitive. FB jsSDK it is an API itself and it is expected to be able to navigate through pages of the response by itself and using same means, no?
实际上它比前辈描述的更简单,并且有点直观。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
}
}
Obviously this will request for next pages as long as there is a next key defined but s proving the concept.
显然,只要定义了下一个键但证明了这个概念,这将要求下一页。