简体   繁体   中英

Error using the Facebook Open Graph API when logging in

How do you use the open graph API to display a facebook login button, and get the username and email after a successful login? I've tried this but with no success.

I have this in the head section:

<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
    FB.init({
        appId: '12345', cookie: true,
        status: true, xfbml: true
    });          

    FB.api('/me', function (user) {
        if (user != null) {
            alert(user.name);
        }
    });
</script>

I placed <div id="fb-root"></div> at the very end just before the </body> tag. So far so good. My <fb:comments> and <fb:comments-count> work fine from any page on my site. But I am unable to get my login to work (it says I don't have fb-root defined)

I have this somewhere in the middle of my page:

<fb:login-button perms="email,user_checkins">Login with Facebook</fb:login-button>

After submitting on the login window, I get a js error that says fb-root div not defined. But I do have it at the end of the page.

Try with Asynchronous Loading

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

<script type="text/javascript">
  window.fbAsyncInit = function() {
    FB.init({
      appId: '12345',
      cookie: true,
      status: true,
      xfbml: true
    });

    FB.api('/me', function(user) {
      if (user != null) {
        alert(user.name);
      }
    });

  };

  (function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

Wrap the initialization inside a function that you call at the very end, ie :

<html>
    <head>
        <script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
        <script type="text/javascript">
            function fbInit() {
                FB.init({
                    appId: '12345', cookie: true,
                    status: true, xfbml: true
                });          
            }       
            if(FB.getSession() != null) {
                // user logged in, continue with the program.  
            };
        </script>
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
            fbInit();
        </script>
    </body>
</html>

Or, even better, inside a $(document).ready() (using jQuery)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM