我正在尝试通过javascript SDK下载Facebook墙上的帖子。我设法对前25个帖子进行了调用,但是当我尝试获取pageing.next并使用循环将其馈送到新的调用中时又遇到麻烦,然后对其进行迭代,直到没有更多页面可用为止。
该代码产生同一页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'});
您需要学习如何处理异步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的时间非常重要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句