为什么需要FB.getLoginStatus?

时间:2013-06-30 00:10:12

标签: javascript facebook facebook-graph-api facebook-authentication

我一直在努力将Facebook Login与我的网站整合,到目前为止,我一直在成功;但是,我仍然有一些疑问。

在我的主页上;我有一个a href按钮,它会触发一个Javascript函数,它会提示用户弹出窗口登录Facebook;如果这是第一次,将提示用户另一个要求权限的弹出窗口!

用户登录后(并接受权限); (s)他将使用document.location.href重定向到另一个页面;到目前为止,一切都很完美。接下来我想做的是:

我想 - 在加载用户被重定向到的页面时 - 显示欢迎消息(欢迎[email]) - 然后我想根据一些数据库信息动态生成一些元素(动态)附在用户名上。

我试图在Javascript中执行此操作:

<script>
$('document').ready(function(){

window.fbAsyncInit = function() {
    FB.init({
    appId   : '[my app id]',
    oauth   : true,
    status  : true, // check login status
    cookie  : true, // enable cookies to allow the server to access the session
    xfbml   : true // parse XFBML
    });

    $(document).trigger('fbload');
};

$(document).on('fbload', function(){
    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            FB.api('/me', function(response) {
            user_email = response.email; //get user email
            // Here, I can display the welcome message :)
            });
        } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook,
            // but has not authenticated your app
        } else {
            // the user isn't logged in to Facebook.
            }
        });
    });
});
</script>

此代码工作正常:) - 但是,如果我从函数中删除FB.getLoginStatus,这将导致以下代码:

$(document).on('fbload', function(){
    FB.api('/me', function(response) {
    console.log(response);
    user_email = response.email; //get user email
    console.log(user_email);
    // Here, I can display the welcome message :)
});

我得到user_email的以下输出:

undefined

我似乎无法理解这一点!由于FB.getLoginStatus仅检查用户是否已登录;为什么它(或缺少它)会破坏函数调用FB.api

如果有人能解释这里实际发生的事情的逻辑,我将不胜感激!

注意:无论如何,我最终可能会使用FB.getLoginStatus,但我主要关注正在发生的事情的逻辑!

1 个答案:

答案 0 :(得分:0)

你的 FB.api('/ me',函数(响应){函数无法在没有由 FB.getLoginStatus提供的有效访问令牌的情况下工作(函数(响应){ 功能。

您可以在浏览器的控制台中通过将代码更改为:

来查看
    $(document).on('fbload', function(){
        FB.getLoginStatus(function(response) {
            console.log(response);  //CHANGE
                FB.api('/me', function(response) {
                    user_email = response.email; //get user email
                    console.log(response);  //CHANGE
                });
            });
        });

这是因为 FB.api('/ me',函数(响应){正在询问有关当前FB用户的各种数据(姓名,性别,家乡,教育,用户名,引号等)。 。),所以Facebook只是确保你让用户登录你的应用程序。

相关问题