你最好的選擇將是通過調用設定的功能,而不是分配這裏面變量:
(function(w) {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user’s ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
w.fb_user_id = response.authResponse.userID;
w.accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
})(window);
再後來就在你的頁面(提供的電話不依賴於緊接本之一),你可以作爲全局變量fb_user_id
(也稱爲window.fb_user_id
,
)訪問頁面上任意位置的變量如果您需要在用戶標識準備就緒後立即運行代碼,則需要使用回調如果您使用的是jQuery 1.5你也可以使用jQuery Deferreds來解決同步性問題:
var getUserId = function() {
return $.Deferred(function(d) {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user’s ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var auth = response.authResponse;
d.resolve(auth.userID, auth.accessToken);
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
d.reject();
} else {
// the user isn't even logged in to Facebook.
d.reject();
}
});
}).promise();
};
getUserId()
.done(function(userId, token) {
// userId and token are available in here
})
.fail(function() {
// run some code in here if not authorized
// or something else failed;
});
來源
2012-03-05 00:56:45
Eli
那麼我怎樣才能使用這個函數w.fb_user_id? – 2012-03-05 01:02:13
我無法訪問。我試過「console.log(fb_user_id);」我得到了無法理解的錯誤。這是一個在標籤頁中工作的Facebook應用程序。這影響什麼? – 2012-03-05 01:12:49
就像我說的,使用這種方法,你將無法立即訪問用戶ID,因爲它被設置爲_asynchronously_。我將提供另一種選擇的回調機制。 – Eli 2012-03-05 01:16:05