简体   繁体   中英

Fb.api undefined user

I have the following problem:

Once the user is logged in facebook if I run the following code:

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

It pops up an alert with "Udefined" written.

But if I change the code in the following way:

FB.api( /[MY_REAL_FACEBOOK_ID], function(user) {
      alert(user.name);
});

It response in the correct manner.

How it is possible ? Why '/me' never works ?

Use the below code to overcome the Undefined problem:

window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : your_app_id,                        
      status     : true,                                 
      xfbml      : true                                 
    });

    // Additional initialization code such as adding Event Listeners goes here

    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            alert("connected");
            connecter=true;
            FB.api('/me', function(user) {
                alert(user.name);
                alert(user.first_name);
                alert(user.last_name);
                alert(user.email);
            });
        } 
    });

I think you might be querying "/me" in context of the app rather than the user. The documentation is not as explicit as it could be, but I've had the same issue.

Are you able to use FB.getLoginStatus ?

After I have FB.init set up, I make a call to FB.getLoginStatus similar to what is found below. There might be a better way on how to do this, but it works for me.

Hopefully this helps:

 FB.getLoginStatus(function (response) {

            if (response.session) {
                // logged in and connected user, someone you know

                graphUrl = "https://graph.facebook.com/me?access_token=" +         response.session.access_token + "&callback=displayUser"
                var script = document.createElement("script");
                script.src = graphUrl;
                document.body.appendChild(script);


            } else {
                // no user session available, someone you dont know

            }});


 function displayUser(user) {

        alert(user.name);
    }

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