2012-11-04

FaceBook API for JavaScript - FB.api

FB.api

FB.api 是 Facebook JavaScript SDK 用來呯叫 Graph API 或 Deprecated REST API (舊的 API 除非是 Graph API 無法達到的效果,不然不建議使用。) 的 function。

說明範例

取得 facebook Platform page 資料:

 FB.api('/platform', function(response) {
  alert(response.company_overview);
 });
如果有一個通過身份驗證的使用者,可以取得使用者資料:
 FB.api('/me', function(response) {
  alert(response.name);
 });
從 Facebook Platform Page 取得最近發表的 3 筆資料:
 FB.api('/platform/posts', { limit: 3 }, function(response) {
  for (var i=0, l=response.length; i < l; i++) {
   var post = response[i];
   if (post.message) {
    alert('Message: ' + post.message);
   } else if (post.attachment && post.attachment.name) {
    alert('Attachment: ' + post.attachment.name);
   }
  }
 });
如果有一個通過身份驗證的使用者並取得 publish_stream 的權限,要發佈一筆資料在他們的 洋鴨牆:
 var body = 'Reading JS SDK documentation';
 FB.api('/me/feed', 'post', { message: body }, function(response) {
  if (!response || response.error) {
   alert('Error occured');
  } else {
   alert('Post ID: ' + response.id);
  }
 });
或者,想要刪除以前發布的資料:
 var postId = '1234567890';
 FB.api(postId, 'delete', function(response) {
  if (!response || response.error) {
   alert('Error occured');
  } else {
   alert('Post was deleted');
  }
 });
建議直接使用 Facebook API ,可以提高應用程式的性能。
目前可狦的 API 範圍幾手函蓋所有的 Facebook 的資料,如 姓名和大頭照,如果你知道用戶的 id 或 資料,可以根據連接狀態且用戶授權,你的應用程式可以取得 Facebook 提供的資料。

Old REST API

FB.API也可以使用 Old REST API。例如: 呼叫 links.getStats:

  FB.api(
   {
    method: 'links.getStats',
    urls: 'facebook.com,developers.facebook.com'
   },
   function(response) {
    alert('Total: ' + (response[0].total_count + response[1].total_count));
   }
  );
 

FB.api 參數

名稱類型說明
path String URL 路徑
method String http 傳輸方式(預設 "GET")徑
params Object 用於查詢的參數
cb Function callback function 用來處理 response 資料

參考資料: