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

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

问题描述:

我想初始化facebook javascript sdk并在用户点击index.html页面上的链接后检查登录状态。由于某种原因,这不会工作。 jQuery正在工作,当我单独测试init代码时,它可以正常工作,但当我将它放在一起时,它停止工作。任何想法为什么?如何使用jquery事件触发window.fbAsyncInit

这是我的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> 

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

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

$('document').ready函数外分配处理函数window.fbAsyncInit

+0

我试着将javascript:window.fbAsyncInit()分配给其中一个链接中的href,但它不起作用。这是你在$(document).ready函数之外赋值处理函数的意思吗? – Spilot 2013-03-07 03:15:48

+0

为什么要在点击链接时运行此代码?不,您希望它尽快运行 - 以便在您想要使用SDK时准备好SDK。只需将其放置在现成的处理程序的外部,就在(现有的)

+0

我希望用户在不立即提示登录或注册的情况下到达主页。我只希望在点击主页上的两个链接之一时发生这种情况。 – Spilot 2013-03-07 14:18:14