gpt4 book ai didi

javascript - 为什么这里需要FB.getLoginStatus?

转载 作者:行者123 更新时间:2023-11-28 09:03:38 27 4
gpt4 key购买 nike

我一直致力于将 Facebook Login 与我的网站集成,到目前为止,我已经取得了大部分成功;但是,我仍然有一些疑问。

在我的主页上;我有一个 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 输出:

未定义

我似乎无法理解其中的逻辑!由于 FB.getLoginStatus 只检查用户是否登录;为什么它(或缺少它)会中断函数调用 FB.api

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

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

最佳答案

如果没有 FB.getLoginStatus(function(response) { 提供的事件访问 token ,您的 FB.api('/me', function(response) {) 函数将无法工作 功能。

您可以通过将代码更改为以下内容在浏览器的控制台中看到这一点:

    $(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', function(response) { 正在询问有关当前 FB 用户的各种数据(姓名、性别、家乡、教育程度、用户名、引言...... .),因此 Facebook 只是确保您让该用户登录到您的应用程序。

关于javascript - 为什么这里需要FB.getLoginStatus?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com