从函数返回FB.getLoginStatus

时间:2012-01-19 15:02:29

标签: facebook-graph-api facebook

当我运行以下脚本(仅相关代码段)而不是返回有效的FB.getLoginStatus时,我无法弄清楚为什么fb_login_status_response在控制台中返回“未捕获的ReferenceError:fb_login_status未定义”。任何想法/反馈将不胜感激。谢谢!

<script>
    function load_fb(){
        window.fbAsyncInit = function() {
            FB.init({
                appId      : '251975954634982', // App ID
                //channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
                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
                }); // closes FB.init
            fb_login_status = FB.getLoginStatus(function(response){
                console.log("FB.getLoginStatus: ", response.status);
                // NOTE - the line above does log an accurate response.status in the console!
                response.status;
                // NOTE - I've tried putting the return statement here, but that doesn't work.
            });
        };
        return fb_login_status; // NOTE - this return statement is what generates the "Uncaught ReferenceError:..." in console
    }   

    // Load FB SDK Asynchronously
    (function(d){
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));


    $(document).ready(function(){
        sb_session_status = checkIfSignedIn();
        if (sb_session_status == "valid"){
            $(".loggedIn").css("display","block");
            // Block of code for logged-in users goes here
        }
        else{
            fb_login_status_response = load_fb();
            console.log("fb_login_status_response: ", fb_login_status_response);
            // NOTE - else clause here to check if user signed-in via facebook
        }
    });
</script>

1 个答案:

答案 0 :(得分:2)

由于FB.getLoginStatus()调用是异步(非同步),因此您需要将回调函数传递给checkIfSignedIn()函数,以便可以运行它。请参阅:https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

var checkIfSignedIn = function(callbackFn) {
    FB.getLoginStatus(function(response){
        console.log("FB.getLoginStatus: ", response.status);

        if($.isFunction(callbackFn)) {
            callbackFn(response.status=="connected" ? "valid" : "other");
        }
    });
};



$(document).ready(function() {
    checkIfSignedIn(function(sb_session_status){

        if (sb_session_status == "valid"){
            // DO SOMETHING with the logged in user
            $(".loggedIn").css("display","block");
        } else {
            // DO SOMETHING to get the user logged in
        }

    });
});