8

谁能告诉我 FB API 是如何工作的。这看起来是一个基本问题,但我真的很困惑。

问题:我有onlogin()。当我单击登录按钮时,我希望它会调用此函数。但是在我粘贴的代码中:我看到先打印警报测试,然后调用 FB.api。

因此,看起来首先调用了onlogin,然后调用了FB API ...有没有办法我只能调用这个函数一次。

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

      window.fbAsyncInit = function() {
          FB.init({appId: 'XXX', status: true, cookie: true, xfbml: true});

      };
      (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);
      }());

    function checkFacebookLogin() {
    FB.api('/me', function(response) {
        alert("Name: "+ response.name + "\nFirst name: "+ response.first_name + "ID: "+response.id);
    });

    alert('test');

    }

    </script>


 <p id="fb_login_button_1"><fb:login-button  onlogin="checkFacebookLogin();"  size="medium" scope="user_about_me">Sign in using Facebook</fb:login-button></p>


</body>v

我的主要问题是该函数应该只被调用一次......但它被调用了两次。

4

2 回答 2

7
    <body>
        <div id="fb-root"></div>
<script>

      window.fbAsyncInit = function() {
          FB.init({appId: 'XXX', status: true, cookie: true, xfbml: true});

      };
      (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);
      }());

    function fetchUserDetail()
    {
        FB.api('/me', function(response) {
                alert("Name: "+ response.name + "\nFirst name: "+ response.first_name + "ID: "+response.id);
            });
    }

    function checkFacebookLogin() 
    {
        FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
            fetchUserDetail();
          } 
          else 
          {
            initiateFBLogin();
          }
         });
    }

    function initiateFBLogin()
    {
        FB.login(function(response) {
           fetchUserDetail();
         });
    }
    </script>


 <input type="button" value="Sign in using Facebook" onclick="checkFacebookLogin();"/>


</body>
于 2012-08-07T05:52:57.833 回答
1

对 FB API 的请求调用是异步的。这意味着一旦发送请求,代码将不会等待请求完成。因此,您会在返回 API 调用之前获得警报测试。所有 FB API 调用都是异步的,如果您尝试使它们同步,那么您的浏览器将挂起。

谢谢考希克

于 2012-08-03T05:41:44.670 回答