这是我抛出Uncaught ReferenceError: FB is not defined
的代码。如果我删除window.fbAsyncInit
方法并在<script src="//connect.facebook.net/en_US/all.js"></script>
<head>
,它会同步正常工作
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript">
function login()
{
FB.login
(
function( response )
{
if ( response.authResponse )
{
FB.api
(
"/me",
function( response )
{
document.getElementById( "profile_name" ).innerHTML = response.name;
document.getElementById( "list" ).innerHTML = "http://graph.facebook.com/" + response.id + "/friends";
}
)
}
}
);
}
function getFriends() {
alert('1');
FB.api('/me/friends', function(response) {
//alert('2:'+response.data);
if(response.data) {
$.each(response.data,function(index,friend) {
//alert(friend.name + ' has id:' + friend.id);
$( "list" ).append = response.name;
});
} else {
alert("Error!");
}
});
}
</script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function()
{
FB.init
(
{
appId : "109036532604620",
channelUrl:"http://localhost/testsaav/channel.html",
status : true,
cookie : true,
oauth : true
}
);
};
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert('connected');
} else if (response.status === 'not_authorized') {
// not_authorized
} else {
// not_logged_in
}
});
(function(d, debug){
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" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ true));
</script>
<a href="javascript:getFriends();">Login</a>
<img id="profile_pic"/>
<pre id="list"></pre>
<div id="profile_name"></div>
</body>
</html>
答案 0 :(得分:1)
尝试移动
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert('connected');
} else if (response.status === 'not_authorized') {
// not_authorized
} else {
// not_logged_in
}
});
此代码在FB.init函数之后但在window.fbAsyncInit函数内部,例如
window.fbAsyncInit = function()
{
FB.init
(
{
appId : "109036532604620",
channelUrl:"http://localhost/testsaav/channel.html",
status : true,
cookie : true,
oauth : true
}
);
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert('connected');
} else if (response.status === 'not_authorized') {
// not_authorized
} else {
// not_logged_in
}
});
};
您将从https://developers.facebook.com/docs/reference/javascript/处的示例中注意到,您的初始化代码应该在asyncinit方法中的init方法之后才能正常运行。这样可以确保在加载SDK后以正确的顺序调用事物