您好我正在编写代码以通过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是否正在加载。请提出一种方法来实现这一目标。
答案 0 :(得分:2)
方法login()
无法访问,因为它位于本地范围内。
如果您希望在该范围之外使用function login() {
,则需要将其设置为全局或部分全局命名空间。
更改
function login() {
到
window.login = function () {
答案 1 :(得分:1)
首先,将这些函数移出window.fbAsyncInit。因为在当地范围内无法访问它们。
然后,您可以拥有一个仅在加载JS-SDK时设置为true的标志,并且您可以“阻止” window.fbAsyncInit 之外的任何进程直到该标志已设定。类似的东西:
var isLoaded = false;
window.fbAsyncInit = function()
{
isLoaded = true;
...
...
}
function myFunc(myVar)
{
if(isLoaded)
{
// Do FB related stuff
}
}