2011-03-26 82 views
0

如何使用開放圖API顯示Facebook登錄按鈕並在成功登錄後獲取用戶名和電子郵件?我試過這個,但沒有成功。登錄時使用Facebook Open Graph API時出錯

我這頭部分:

<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    FB.init({ 
     appId: '12345', cookie: true, 
     status: true, xfbml: true 
    });   

    FB.api('/me', function (user) { 
     if (user != null) { 
      alert(user.name); 
     } 
    }); 
</script> 

我只是</body>標記之前<div id="fb-root"></div>在最後。到現在爲止還挺好。我的<fb:comments> and <fb:comments-count>可以在我網站上的任何頁面上正常工作。但我不能讓我的登錄工作(它說我沒有做FB-根定義)

我有這樣的地方在我的頁面的中間:

<fb:login-button perms="email,user_checkins">Login with Facebook</fb:login-button> 

提交在登錄後窗口,我得到一個js錯誤,說fb-root div沒有定義。但是我確實已經在頁面的最後。

+0

如果可以的話,請使用php方案..好得多... – Shouvik 2011-03-26 09:50:42

+0

也許不相關,但不要在沒有確定您之前登錄的情況下使用/我。查看我的答案以獲得更好的選擇。 – Aleadam 2011-03-30 23:52:16

回答

0

Asynchronous Loading

<div id="fb-root"></div> 

<script type="text/javascript"> 
    window.fbAsyncInit = function() { 
    FB.init({ 
     appId: '12345', 
     cookie: true, 
     status: true, 
     xfbml: true 
    }); 

    FB.api('/me', function(user) { 
     if (user != null) { 
     alert(user.name); 
     } 
    }); 

    }; 

    (function() { 
    var e = document.createElement('script'); 
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
    e.async = true; 
    document.getElementById('fb-root').appendChild(e); 
    }()); 
</script> 
+1

另外,您應該在腳本標記中放置'#fb-root' div _before_。這可確保在腳本執行之前對其進行定義。 – Matthew 2011-04-05 17:54:06

+0

@Matthew fb-root補充:) – haha 2011-04-06 01:19:16

0

裹在函數內部初始化,您撥打的盡頭,即嘗試:

<html> 
    <head> 
     <script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script> 
     <script type="text/javascript"> 
      function fbInit() { 
       FB.init({ 
        appId: '12345', cookie: true, 
        status: true, xfbml: true 
       });   
      }  
      if(FB.getSession() != null) { 
       // user logged in, continue with the program. 
      }; 
     </script> 
    </head> 
    <body> 
     <div id="fb-root"></div> 
     <script type="text/javascript"> 
      fbInit(); 
     </script> 
    </body> 
</html> 

,或者甚至更好,一個$(document).ready()(使用jQuery)內