FB.api每次都不工作

时间:2011-11-14 07:32:22

标签: javascript facebook-graph-api facebook-javascript-sdk

我是Facebook Javascript SDK的新手。我正在尝试使用此API创建应用程序。但是在使用FB.api方法时运气不好。不知何故,我的FB.api方法每次都无法正常工作。有时它会给出响应(我只是访问response.name),而其他时候它不会被正确调用。

window.fbAsyncInit = function() {
FB.init({
  appId      : 'my_app_id', // App ID
  status     : true, // check login status
  cookie     : true, // enable cookies to allow the server to access the session
  oauth      : true, // enable OAuth 2.0
  xfbml      : true  // parse XFBML
});
FB.getLoginStatus(function(response) {
  if (response.authResponse) {
   alert('user is:'+response.status); 
   userId = response.authResponse.userID;
   FB.api('/me',function(response) {
   alert('Inside FB.api function');
   document.getElementById("userInfo").innerHTML = 'Welcome <img src="https://graph.facebook.com/'+ response.id + '/picture" style="margin-right:5px"/>' +response.name + '!';
    });
    }
});
};

其他方法FB.ui和FB.getLoginStatus以及类似Facebook的按钮正在按预期工作,但只有FB.api无法像其他方式一样工作。不是为什么?请帮我识别问题。

3 个答案:

答案 0 :(得分:2)

我遇到了完全相同的问题。这个答案指出了我正确的方向:

FB.api does not work when called right after FB.init

要解决我的问题,我必须订阅正确的事件。就我而言,在FB.init之后是'auth.authResponseChange'

FB.Event.subscribe('auth.authResponseChange', function(){
    FB.api('/me',function(r){
    console.log(r.id);
     if (!r || r.error) {
        alert('Error occured');
      } else {
        alert(r.name);
      }         
    });
});

答案 1 :(得分:0)

该代码适合我,但您可能想尝试重命名您的响应变量。在FB.api回调中,你实际上有两个响应变量,这无疑会引起问题。尝试更改它们,看看你是否得到不同的结果。

FB.getLoginStatus(function(loginResponse) {
  if (loginResponse.authResponse) {
   alert('user is:'+loginResponse.status); 
   userId = loginResponse.authResponse.userID;
   FB.api('/me',function(apiResponse) {
   alert('Inside FB.api function');
   document.getElementById("userInfo").innerHTML = 'Welcome <img src="https://graph.facebook.com/'+ apiResponse.id + '/picture" style="margin-right:5px"/>' +apiResponse.name + '!';
    });
    }
});

可能您网页上还有其他内容影响了这一点。你有一个指向你页面的链接吗?

答案 2 :(得分:0)

我遇到了同样的问题。 FB.api在我的应用程序中的某个时刻停止了默默工作。我注意到这是由于DOM的操作:

<div id="fb-root"></div>

重复或任何东西。你应该检查这一点。看起来像Johan Strydom的问题。