Попробуйте этот код:
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '270423476307006',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.getLoginStatus(function(response) {
onStatus(response); // once on page load
FB.Event.subscribe('auth.statusChange', onStatus); // every status change
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<h1>Login, Logout, Name and Profile Picture</h1>
<div id="account-info"></div>
<script>
/**
* This assumes the user is logged in and renders their profile picture,
* name and a logout link.
*/
function showAccountInfo(resp) {
if( !resp.userID ) {
// we shouldn't be here
return;
}
FB.api(
{
method: 'fql.query',
query: 'SELECT name,uid,pic_square FROM user WHERE uid='+resp.userID
},
function(response) {
document.getElementById('account-info').innerHTML = (
'<img src="' + response[0].pic_square + '"> ' +
response[0].name +
' <img onclick="FB.logout()" style="cursor: pointer;"' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">'
);
}
);
}
/**
* This assumes the user is logged out, and renders a login button.
*/
function showLoginButton() {
document.getElementById('account-info').innerHTML = (
'<img onclick="FB.login()" style="cursor: pointer;"' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">'
);
}
/**
* This will be called once on page load, and every time the status changes.
*/
function onStatus(response) {
if (response.authResponse) {
showAccountInfo(response.authResponse);
} else {
showLoginButton();
}
}
</script>
</body>
Теперь давайте объясним, что мы сделали:
- Мы используем асинхронную загрузку, чтобы гарантировать, что
FB.getLoginStatus()
будет запущен ТОЛЬКО после успешной загрузки библиотеки
- Поскольку вы устанавливаете для
oauth
значение true, вам необходимо изменить код для работы с новыми ответами (см. Эту запись ) (может потребоваться изменить настройки приложения)
- Исходя из # 2, текущий идентификатор пользователя для использования в
showAccountInfo()
будет доступен с помощью response.authResponse.userID