2012-01-19 46 views
0

我不知道为什么fb_login_status_response在运行下面的脚本(仅适用于相关代码片段)而不是返回有效的FB时返回控制台中的“Uncaught ReferenceError:fb_login_status未定义”。 getLoginStatus。任何想法/反馈将不胜感激。谢谢!从函数返回FB.getLoginStatus

<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> 

回答

2

由于FB.getLoginStatus()呼叫异步(不syncronous),那么你就需要在回调函数传递给你的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 
     } 

    }); 
}); 
+0

超级有用。谢谢!我还没有机会在我的程序中进行测试,但您的解释很有意义。我会确认一次我的工作。 –