我运行了一个从以下位置复制的示例:
http://developers.facebook.com/docs/reference/javascript/
http://developers.facebook.com/docs/reference/javascript/FB.api/
(我只更改了我的APP_ID)
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/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
});
FB.api('/platform/posts', { limit: 3 }, function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
};
// 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>
浏览器中没有显示任何内容。控制台(Opera 11)中没有JavaScript错误。为什么不起作用?
答案 0 :(得分:1)
我遇到了同样的问题,并意识到该示例未正确解析响应。该对象有一个属性 data ,实际上是要解析的数组。
另一点是您需要一个令牌来执行此操作。所以你的代码应该是:
<div id="fb-root"></div>
<script>
var fbToken; // Highly recommended to make it global
window.fbAsyncInit = function()
{
FB.init({
appId : 'MY_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/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
});
FB.login(function(response)
{
if (response.authResponse)
{
fbToken = response.authResponse.accessToken; // Save it for another requests
FB.api('/platform/posts', {limit:3}, function(response){
for (var i=0, l=response.data.length; i<l; i++)
{
var post = response.data[i];
if (post.message)
{
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name)
{
alert('Attachment: ' + post.attachment.name);
}
}
});
} else {
// User did not accept oAuth
}
});
}
// 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>
答案 1 :(得分:0)
看起来您还没有登录。在运行这部分代码之前,您需要先验证用户是否先获取oauth令牌:
FB.api('/platform/posts', { limit: 3 }, function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
请参阅:http://developers.facebook.com/docs/reference/javascript/FB.login/