【发布时间】:2013-05-23 13:28:15
【问题描述】:
我成功运行 FB.Event.subscribe 并且可以从该函数中输出 uid 和 accesstoken - 但是 我想知道如何从基本上任何地方访问 uid 和 accesstoken ?
我最初的想法是我需要在函数之外声明一个全局 uid 和 accesstoken var - 但是到目前为止我没有运气 - 在尝试输出全局 var 时我只得到 undefined
我的代码就在<body>标签之后:
<body>
<div id="fb-root"></div>
<script>
//Declaring global var for uid and token
var uid;
var accessToken;
$(document).ready(function(){
function facebookReady(){
FB.init({
appId : '357646666347166', // App ID
channelUrl : '//localhost/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
$(document).trigger("facebook:ready");
}
if(window.FB) {
facebookReady();
} else {
window.fbAsyncInit = facebookReady;
}
});
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
我的代码放在关闭 </body> 标记之前 - 这也是我尝试访问全局 uid 和令牌的地方:
<script>
$(document).on("facebook:ready", null, function(){
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// Setting the uid + token
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
//
}
});
// Trying to access the UID OR TOKEN HERE:
console.log(uid);
console.log(accessToken);
// Trying to access the UID OR TOKEN HERE:
});
</script>
<!-- some included js file where I also want to access the UID -->
<script src="js/animation.js"></script>
【问题讨论】:
-
这是因为 JS SDK 是异步工作的——当你尝试访问它时,数据还没有到达。一旦回调函数将值分配给变量,您就可以“从任何地方”访问它们——但之前不行。
-
您好 cbroe,非常感谢您的评论。您是否有任何关于方法的建议,可以在我尝试在我发布的代码范围内访问它之前等待它被设置?
标签: facebook facebook-graph-api facebook-javascript-sdk