我不知道如何在api FB.login中同步,这是我的代码:
function getAccesToken(){
var access_token = "";
FB.login(function(response) {
if (response.authResponse) {
access_token = FB.getAuthResponse()['accessToken'];
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: '' });
return access_token;
}
当我调用函数
时var access_token = getAccessToken();
但它返回空字符串。如何将其修复为同步?
答案 0 :(得分:1)
你无法使这种同步 - 如果可以的话,这将是非常糟糕的做法。而是在包含访问令牌的FB.login
回调处理程序中调用函数。试试这个:
function getAccesToken() {
FB.login(function(response) {
if (response.authResponse) {
loginComplete(FB.getAuthResponse()['accessToken']);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: '' });
}
function loginComplete(token) {
console.log(token);
// do something here, now the user is logged in...
}
答案 1 :(得分:1)
FB.login
,并且必须使用FB.login
的回调函数异步获取访问令牌 - 访问令牌将在响应值中。例如:
document.getElementById('loginBtn').addEventListener('click', function() {
FB.login(function(response) {
if (response.authResponse) {
doSomethingWithTheToken(response.authResponse.accessToken);
}
}, {scope: 'email,public_profile', return_scopes: true});
}, false);
function doSomethingWithTheToken(token) {
console.log(token);
}
来源(以及有关JavaScript SDK的更多信息):http://www.devils-heaven.com/facebook-javascript-sdk-login/