如何使用Jquery事件触发window.fbAsyncInit

时间:2013-03-06 18:18:56

标签: jquery facebook-javascript-sdk

我想在用户点击index.html页面上的链接后初始化facebook javascript sdk并检查登录状态。出于某种原因,这不会起作用。 jQuery正在运行,当我单独测试init代码时,它可以工作,但是当我把它放在一起它就会停止工作。知道为什么吗?

这是我的index.html页面:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

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

//这个jquery应该触发init进程

$('document').ready(function(){
          $('a').click(function(){
             alert("this works");

  // Additional JS functions here
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '39672*******', // App ID
      channelUrl : '//http://spilot.koding.com/channel.html', // Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });

    // get login status
FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    // connected: redirect to start scene page
    alert("testing");
  } else if (response.status === 'not_authorized') {
    // not_authorized
    login();
  } else {
    // not_logged_in
    login();
  }
 });
  };

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

//显示登录框

   function login() {
    FB.login(function(response) {
        if (response.authResponse) {
            // connected
            alert("connected");
        } else {
            // cancelled
        }
    });
}
});
});


</script>





<div id="findScene"><a href=""><h1>Find</h1></a></div>
<div id="startScene"><a href=""><h1>Host</h1></a></div> 
</body>

</html>

1 个答案:

答案 0 :(得分:2)

JS SDK是异步加载的 - 它可能在整个页面/其余资源之前完成。

因此,将函数传递给window.fbAsyncInit可能已经很晚了 - 因为只有在$('document').ready触发时才会这样做。

将处理程序功能分配到window.fbAsyncInit功能之外的$('document').ready