【问题标题】:gapi is not defined error comes when using with requirejs与requirejs一起使用时出现gapi未定义错误
【发布时间】:2016-12-06 05:09:07
【问题描述】:

我正在尝试使用 requireJS 加载 google API 文件,但出现以下错误, 有人认为我可以低估 GP 文件在谷歌调用之前加载

“gp.js:23 Uncaught ReferenceError: gapi is not defined”

这里是代码

gp.js 文件

function logout()
{
    gapi.auth.signOut();
    location.reload();
}
function login() 
{
    var myParams = {
        'clientid' : '900278902057-ppqm358qrhki089danipqguj3i4ir70i.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.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'
    };
    gapi.auth.signIn(myParams);
}

function loginCallback(result)
{
    if(result['status']['signed_in'])
    {
        var request = gapi.client.plus.people.get(
            {
                'userId': 'me'
            });
        request.execute(function (resp)
                        {
            var email = '';
            if(resp['emails'])
            {
                for(i = 0; i < resp['emails'].length; i++)
                {
                    if(resp['emails'][i]['type'] == 'account')
                    {
                        email = resp['emails'][i]['value'];
                    }
                }
            }




            var str = "Name:" + resp['displayName'] + "<br>";
            //                str += "Image:" + resp['image']['url'] + "<br>";
            //    str += "<img src='" + resp['image']['url'] + "' /><br>";

            // str += "URL:" + resp['url'] + "<br>";
            str += "Email:" + email + "<br>";
            str += "DOB:" + resp['birthday'] + "<br>";
            str += "Gender:" + resp['gender'] + "<br>";
            document.getElementById("profile").innerHTML = str;
        });

    }

}
function onLoadCallback()
{
    gapi.client.setApiKey('AIzaSyBy08qpAjR9U1nKaZ5H1MmwTuthspQPNqY');
    gapi.client.load('plus', 'v1',function(){});
}

还有 requirejs 文件 - main.js

require.config({
    shim: {

        'jquery': {
            exports: '$'
        },
/*        'backbone': {
            deps: ['jquery', 'underscore'],
        },*/
        'googleplus' : {
            deps: ['jquery'],
            exports: 'gapi'
        },


    },
    paths: {
        'jquery': '//code.jquery.com/jquery-1.11.0.min',
        'googleplus': 'https://apis.google.com/js/plus.js?onload=init',

    }
})
require(['gp']);

和 html 按钮

 <input type="button"  value="Login" onclick="login()" />
<input type="button"  value="Logout" onclick="logout()" />

当我尝试不使用 requireJS 时,相同的代码可以完美运行,但问题是我必须使用 requireJS

【问题讨论】:

    标签: javascript jquery requirejs


    【解决方案1】:

    gp.js 必须是一个模块。

    define(['jquery', 'googleplus'], function($, gapi) {
        # your code
    
        window.loginCallback = function (result) {
            if (result['status']['signed_in']) {
                gapi.client.load('plus', 'v1', function () {
                    var request = gapi.client.plus.people.get(
                        {
                            'userId': 'me'
                        });
                    request.execute(function (resp) {
                        var email = '';
                        if (resp['emails']) {
                            for (i = 0; i < resp['emails'].length; i++) {
                                if (resp['emails'][i]['type'] == 'account') {
                                    email = resp['emails'][i]['value'];
                                }
                            }
                        }
    
    
                        var str = "Name:" + resp['displayName'] + "<br>";
                        str += "Email:" + email + "<br>";
                        str += "DOB:" + resp['birthday'] + "<br>";
                        str += "Gender:" + resp['gender'] + "<br>";
                        document.getElementById("profile").innerHTML = str;
                    });
                });
            }
        };
    
        $('#login').click(login);
        $('#logout').click(logout);
    });
    

    并修改模板:

    <input type="button"  value="Login" id="login" />
    <input type="button"  value="Logout" id="logout" />
    

    因为gapi.signIn方法需要全局命名空间中的回调函数,所以loginCallback函数必须是全局的。

    【讨论】:

    • 现在我在 gp.js 第 1 行“未捕获的 SyntaxError: Unexpected token function”中遇到错误
    • 还有那个方括号是什么
    • 对不起,我修正了例子
    • 我以同样的方式做了,但它不起作用,每次都会收到一个新错误 Uncaught ReferenceError: login is not defined
    • 因为loginlogout 现在不是全局函数。
    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2020-07-20
    • 1970-01-01
    • 2014-10-10
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多