2013-04-01 147 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'} 
    );