我成功运行了FB.Event.subscribe并可以从该函数中输出uid
和accesstoken
- 但我想知道我将如何访问uid
和基本上来自任何地方的accesstoken
?
我最初的想法是我需要在函数之外声明一个全局uid和accesstoken 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>
答案 0 :(得分:0)
我用来将我的accessToken存储在一个全局变量中,它没有问题。这里的问题是uid和accessToken都只在各自的脚本标签中有作用域,因此在FB.Event.subscribe中声明的uid和accessToken是它们自己的值;与“全局变量”分开,谁的范围仅限于FB.Event.subscribe。
据说所有你需要的是 FB.getAccessToken()
使用jQuery通过ajax请求检索数据的示例:
$.ajax({
url: "myQuery.php",
data: { accessToken: FB.getAccessToken() }
}).done(function(data) {
doStuff(data);
});
您还可以通过 FB.getUserID()
检索uid