如何在用户使用 Facebook 登录后使用 JS SDK 获取其用户信息

5

我在头部有这样的代码:

<script src="http://connect.facebook.net/en_US/all.js"></script>

然后我有以下这段FB登录按钮代码:
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=myAppId&amp;xfbml=1">
</script><fb:login-button show-faces="false" perms="user_hometown,user_about_me,email,user_address"
autologoutlink="true" width="200" max-rows="1">
</fb:login-button>

当用户使用FB按钮登录后,我该如何进行JS调用以获取他们的姓名、电子邮件、照片等信息呢?

我还发现了一些类似以下代码的内容,但不确定这在哪里使用:

<script>
  FB.init({
    appId  : 'myAppId',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true, // parse XFBML
    channelURL : 'http://www.comehike.com/channel.html', // channel.html file
    oauth  : true // enable OAuth 2.0
  });
</script>

我需要写在上面的代码吗?

谢谢!


您需要FB.init代码来初始化Facebook JavaScript SDK并解析XFBML。 - jBit
1个回答

14
<html>
<head> ... </head>
<body>
    <div id="fb-root"></div>

    <fb:login-button show-faces="false" perms="user_hometown,user_about_me,email,user_address" autologoutlink="true" width="200" max-rows="1"></fb:login-button>


    <!-- put this before the end body tag -->
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
      FB.init({
        appId  : 'myAppId',
        status : true, // check login status
        cookie : true, // enable cookies to allow the server to access the session
        xfbml  : true, // parse XFBML
        channelURL : 'http://www.comehike.com/channel.html', // channel.html file
        oauth  : true // enable OAuth 2.0
      });
    </script>
</body>
</html>

获取已登录用户的数据:

FB.api('/me', function(response) {
  console.log(response);
});

如果一切顺利,response 应该是一个包含你有权限查看的用户数据的 JSON 对象。

用户的图片可以从以下获取:

http://graph.facebook.com/FACEBOOK_USER_ID/picture

您可以使用type参数指定所需的大小。

  • square - 50x50
  • small - 宽度为50像素,高度可变
  • normal - 宽度为100像素,高度可变
  • large - 大约200像素宽,高度可变

例如:

http://graph.facebook.com/FACEBOOK_USER_ID/picture?type=large

@jBut 嗯,我这里有这个东西:http://www.comehike.com/test_fb_connect.php,但是我无法让FB按钮渲染出来。你能查看它的源代码并看到FB代码吗? - Genadinik
顺便问一下,channel.html文件应该放什么内容?我没有这个文件 :) - Genadinik
你的xfbml已被注释掉。 - jBit
嗯,xfbml 没有被注释掉。我取消了注释,但它仍然无法渲染登录按钮...你有什么想法它可能出了什么问题吗? - Genadinik
@Genadinik 让我们在聊天室里继续这个讨论 - jBit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接