如何从另一个js文件调用函数;如何将会话变量传递给另一个js文件

时间:2014-06-10 15:10:40

标签: javascript google-api google-plus

我是Javascript的初学者,并学习如何创建网站。我试图在我的网络应用中添加Google +登录功能,但无法通过javascript传递会话信息。我有2个js文件 - login.js和profile.js。当用户登录时,login.js将运行,并从profile.js加载一个函数。我在index.html文件中包含了这两个脚本但仍然出现此错误:未定义loadProfile 。被困了好几天,真的很感激一些指导!

这是我的代码

index.html

  {head}
    {script src="https://apis.google.com/js/plusone.js"}{/script}
    {script src="https://apis.google.com/js/client:plusone.js"}{/script}
  {/head}
  {body}
  {script type="text/javascript" src="Scripts/profile.js"}{/script}
  {script type="text/javascript" src="Scripts/login.js"}{/script}
  {input type="button" id="login" value="Login" onclick="login()" /}
  {input type="button" id="logout" class="hide" value="Logout" onclick="logout()" /}
  {script type="text/javascript" src="Scripts/logout.js"}{/script}
  {/body}

login.js

function login() {
   var myParams = {
'clientid' : '699XXXXXXX.apps.googleusercontent.com',
'cookiepolicy' : 'single_host_origin',
'callback' : 'loginCallback', 
'approvalprompt':'force',
'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com /auth/plus.profile.emails.read'
 };
gapi.auth.signIn(myParams);
}

function loginCallback(result) {
  if(result['status']['signed_in']) {
  alert("Login Success");
  var obj = gapi.auth.getToken();
  loadProfile();                // Calls loadProfile() from profile.js
  }
 }

profile.js

function loadProfile(){  
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute(loadProfileCallback());
  }  
function loadProfileCallback(obj) {
profile = obj;
email = obj['emails'].filter(function(v) {
    return v.type === 'account';
})[0].value; 
displayProfile(profile);
  }
>>> subsequently it's just some callback functions

1 个答案:

答案 0 :(得分:0)

您可以在文件声明之前在HTML中编写一些内联Javascript:

<script>
    function loadProfile(){  
        var request = gapi.client.plus.people.get( {'userId' : 'me'} );
        request.execute(loadProfileCallback());
    } 
</script>
<script type="text/javascript" src="Scripts/profile.js"></script>
<script type="text/javascript" src="Scripts/login2.js"></script>

通过这种方式,此功能可全局用于所有后续文件。请参阅此答案:Can we call the function written in one JavaScript in another JS file?,它具有与您相同的问题,并且对文件的范围及其用法有很好的解释。