2

嗨,我正在编写代码以通过 facebook 登录用户。我将所有函数与其他 javascript 函数一起存储在一个文件中。我尝试从另一个 javascript 函数调用登录函数并得到以下错误:未定义登录。这是 index.html 的代码

<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<div id="fb-root"></div>
<a href = "#" onClick = "sayhi();">Hi!</a>
</body>
</html>

这是javascript.js

window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : '213443452146381', // App ID from the App Dashboard
      channelUrl : '//http://abc.in/', // Channel File for x-domain communication
      status     : true, // check the login status upon init?
      cookie     : true, // set sessions cookies to allow your server to access the session?
      xfbml      : true  // parse XFBML tags on this page?
    });

    FB.getLoginStatus(function(response) {
    if (response.status === 'connected') 
    {
    alert('connected');
    } 
    else if (response.status === 'not_authorized') {
    alert('not_authorized');
    login();
    } else {
    alert('chillonly');
    login();
    }
    });

    function login() {
    FB.login(function(response) {
        if (response.authResponse) {
            alert('connected');
            testAPI();
        } else {
           alert('not_connected_login');
           testAPI();
        }
    });
    }
    function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
        console.log('Good to see you, ' + response.name + '.');
    });
    }
    // Additional initialization code such as adding Event Listeners goes here

  };

  // Load the SDK's source Asynchronously
  // Note that the debug version is being actively developed and might 
  // contain some type checks that are overly strict. 
  // Please report such bugs using the bugs tool.
  (function(d, debug){
     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" + (debug ? "/debug" : "") + ".js";
     ref.parentNode.insertBefore(js, ref);
   }(document, /*debug*/ false));
// ]]>

function sayhi()
{
alert('Hi');
login();
}

我怀疑facebook jdk是否正在加载。请提出一种方法来实现这一点。

4

2 回答 2

2

该方法login()不可访问,因为它在本地范围内。

如果您想function login() {在该范围之外使用,则需要将其设为全局或某个全局命名空间的一部分。

改变

function login() {

window.login = function () {
于 2012-12-24T14:18:40.470 回答
1
  1. 首先,将函数移出 window.fbAsyncInit。由于在本地范围内,它们无法访问。

  2. 然后,您可以拥有一个仅在加载 JS-SDK 时设置为 true 的标志,并且您可以“阻止” window.fbAsyncInit之外的任何进程,直到设置该标志为止。就像是:

    var isLoaded = false;
    window.fbAsyncInit = function() 
    {
       isLoaded = true;
       ...
       ... 
    }
    
    function myFunc(myVar) 
    {
      if(isLoaded) 
      {
      // Do FB related stuff
      }
    }
    
于 2012-12-24T14:21:49.530 回答