2013-04-01 148 views
0

我正在玩Javascript的Facebook API来尝试从Facebook上拉帖子。我从this page in the documentation.复制代码该函数将访问给定的页面并实际产生响应。但是,response.length和response [i]返回为“undefined”,从而导致循环无法工作。这是为什么发生?为什么这个循环通过Facebook的帖子不工作?

<button onclick="ShowMyPosts()">Show posts</button> 
<script language="javascript" type="text/javascript"> 
    function ShowMyPosts() { 
     FB.api('/TheWalkingDeadAMC/posts', { limit: 3 }, function(response) { 
      console.log(response) 
      console.log(response.length) 
      for (var i=0, l=response.length; i<l; i++) { 
       var post = response[i]; 
       console.log(post) 
       if (post.message) { 
        console.log('Message: ' + post.message); 
       } else if (post.attachment && post.attachment.name) { 
       console.log('Attachment: ' + post.attachment.name); 
      } 
      } 
    } 
) 
console.log("successfully ran function")   
}; 
</script> 

我如何获得访问令牌。这是不正确的?

FB.login(function(response) { 
    if (response.authResponse) { 
     var access_token = FB.getAuthResponse()['accessToken']; 
     console.log('Access Token = '+ access_token); 
     FB.api('/me', function(response) { 
      console.log('Good to see you, ' + response.name + '.'); 
      }); 
    } else { 
     console.log('User cancelled login or did not fully authorize.'); 
     }{scope: 'read_stream'} 
    }); 
+0

您需要访问令牌才能访问页面帖子。确保你已经遵循了这个[如何开始]的每一步(https://developers.facebook.com/docs/howtos/login/getting-started/)教程。 –

+0

我正在获取访问令牌......我已将其编辑到帖子中。它不正确吗? – jumbopap

回答

2

当您查询的图形API - 大多数结果将里面data关键...

使用Graph API Explorer你可以测试你的电话和看到的结果是什么,而无需编写任何代码行。

这是您的Graph API调用测试的direct link。正如你所看到的data拥有的职位。

因此,您需要循环使用response.data而不是response

的代码应该是这样的:

function ShowMyPosts() { 
    FB.api('/TheWalkingDeadAMC/posts', { limit: 3 }, function(response) { 
     console.log(response.data); 
     console.log(response.data.length) 
     for (var i=0, l=response.data.length; i<l; i++) { 
      var post = response.data[i]; 
      console.log(post) 
      if (post.message) { 
      console.log('Message: ' + post.message); 
      } else if (post.attachment && post.attachment.name) { 
      console.log('Attachment: ' + post.attachment.name); 
      } 
     } 
    } 
+1

非常有帮助,谢谢。 – jumbopap

0

我认为这个问题是我的FB.login是不正确的。这是以下正确的代码:

FB.login(
function(response) { 
    if (response.authResponse) { 
     var access_token = FB.getAuthResponse()['accessToken']; 
     console.log('Access Token = '+ access_token); 
     FB.api('/me', function(response) { 
      console.log('Good to see you, ' + response.name + '.'); 
      }); 
    } else { 
     console.log('User cancelled login or did not fully authorize.'); 
     }}, 
    {scope: 'read_stream'} 
    );