为什么这个循环通过facebook帖子不起作用?

时间:2013-04-01 23:56:33

标签: javascript facebook facebook-javascript-sdk

我正在使用Javascript中的Facebook API来尝试从Facebook发布帖子。我从this page in the documentation.复制了代码。该函数将访问给定的页面并实际生成响应。但是,response.length和response [i]返回为“undefined”,因此循环无法工作。为什么会这样?

<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'} 
    }); 

2 个答案:

答案 0 :(得分:2)

当您查询Graph 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 :(得分: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'}  
    );