FB没有定义javascript

Cou*_*uim 16 javascript facebook facebook-graph-api facebook-javascript-sdk

我有FB JS SDK的问题.

我正在尝试获取facebook页面节点的fan_count.

这是我的html文件到我体内的代码:

<script>
  window.fbAsyncInit = function() {
      FB.init({
        appId      : 'your-app-id',
        xfbml      : true,
        version    : 'v2.5'
      });
    };

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>
Run Code Online (Sandbox Code Playgroud)

当我在我的js应用程序上使用它时,我使用它:

init();

function init() {
  var id_fb  = "l214.animaux";
  while (true) {
    console.log("je suis ici");
    FB.api(
      '/' + id_fb +  '/',
      'GET',
      {"fields":"fan_count"},
      function(response) {
        alert(response.fan_count);
      }
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

但错误是FB没有定义.有什么建议 ?

lus*_*chn 18

这是正确的,你需要在JS SDK初始化后使用FB.话虽这么说,你绝对不想在无限循环中调用FB.api,所以我删除了那部分:

<script>
    function init() {
        FB.api(
          '/l214.animaux',
          {"fields":"fan_count"},
          function(response) {
            alert(response.fan_count);
          }
        );
    }

    window.fbAsyncInit = function() {
      FB.init({
        appId      : 'your-app-id',
        xfbml      : true,
        version    : 'v2.5'
      });

      init();
    };

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>
Run Code Online (Sandbox Code Playgroud)

确保从实际服务器运行此命令,不要只在浏览器中打开HTML文件,而不必至少使用本地服务器.


Spa*_*Bao 9

我收到此错误的原因是,我将初始化代码写在一个独立的js文件中,所以当然FB未定义,因为它应该是window.FB

我的代码:

class FacebookUtil {

  static init() {
    // comes from https://developers.facebook.com/docs/javascript/quickstart
    // notice FB should be window.FB
    window.fbAsyncInit = function() {
      window.FB.init({
        appId            : '...',
        autoLogAppEvents : true,
        xfbml            : true,
        version          : 'v2.10'
      });
      window.FB.AppEvents.logPageView();
    };

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }

  static login() {
    window.FB.login(...)
  }

}
Run Code Online (Sandbox Code Playgroud)