1

我一直在致力于将Facebook Login与我的网站进行整合,到目前为止,我一直在成功;不过,我仍然有一些疑问。为什么在这里需要FB.getLoginStatus?

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

用户登录后(并接受权限); (s)他将被重定向到使用document.location.href的另一页;到目前为止,一切工作都很完美。然而,我想接下来要做的事情如下:

我想 - 在加载用户重定向到的页面 - 显示欢迎消息(欢迎[电子邮件]) - 然后我想动态生成少量元素,具体取决于附加到用户名的一些数据库信息。

我尝试这样做,在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,但我主要关心发生了什么的逻辑!

回答

0

FB.api( '/我',功能(响应){功能不能没有活性访问令牌是由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(“/我”,函数(响应){被询问关于当前FB用户的各种数据(姓名,性别,家乡,教育,美国sername,quotes ...),所以Facebook只是确保你有该用户登录到你的应用程序。

+1

但是''response''中''user_email = response.email'没有'response'来自'response'这里:'FB.api('/ me',function(response)...'? – Thuglife

+0

对不起,你是绝对正确的 真正的答案是:你的FB.api('/ me',function(response){无法在没有由FB.getLoginStatus提供的活动访问令牌的情况下工作 您可以仔细检查您的浏览器控制台通过更改您的代码: $(document)。上( 'fbload',函数(){ FB.getLoginStatus(功能(响应){ \t \t的console.log(响应); FB.api( '/我',功能(响应){ USER_EMAIL =响应。电子邮件; //获取用户电子邮件 \t \t \t console.log(response); }); }); }); – ObiVanKaPudji

+0

谢谢;我仍然有兴趣知道'FB.getLoginStatus'提供的是如何实际发生的?我没有看到'FB.api'从'FB.getLoginStatus'中获取任何参数,这部分是我想要澄清的地方! – Thuglife