【问题标题】:Try to display calendar list from Google API using Java Script尝试使用 Javascript 从 Google API 显示日历列表
【发布时间】:2015-04-30 17:19:42
【问题描述】:

我在通过 Google API 显示来自 Google 日历的可访问日历列表时遇到了一些麻烦。我使用 JavaScript 和 AJAX。

我需要使用哪些方法? 我只找到了事件的相关方法,但没有找到日历的显示描述。

谢谢!

【问题讨论】:

  • 你有任何到目前为止你尝试过的示例代码吗?

标签: javascript ajax api calendar


【解决方案1】:

要获得基本的工作模型,您可以按照calendar API site 上的快速入门示例进行操作

该示例有一个名为 listUpcomingEvents() 的函数来获取“主要”日历上的事件。要获取日历列表,请使用以下方法:

function listCalendars()
{
     var request = gapi.client.calendar.calendarList.list();

     request.execute(function(resp){
             var calendars = resp.items;
             console.log(calendars);
     });
}

【讨论】:

  • 您在哪里找到有关 gapi.client.calendar.calendarList.list 的文档? reference docs 仅显示 Java、Python、PHP 和 Ruby,JS Docs 未提及日历。
  • 真的想知道您在哪里找到有关此的文档?
【解决方案2】:

这是我刚刚写的一些代码:

kb.loadAsync('https://apis.google.com/js/client.js', 'onload', 'gapi').then(gapi => {
    gapi.auth.authorize({
        client_id: __GOOGLE_CALENDAR_API_KEY__,
        scope: 'https://www.googleapis.com/auth/calendar',
        immediate: true,
    }, authResult => {
        if(authResult && !authResult.error) {
            gapi.client.load('calendar','v3', () => {
                gapi.client.calendar.calendarList.list({
                    maxResults: 250,
                    minAccessRole: 'writer',
                }).execute(calendarListResponse => {
                    let calendars = calendarListResponse.items;
                    console.log(calendars.map(cal => cal.summary));
                });
            });
        } else {
            console.log('unauthorized');
        }
    });
});

kb.loadAsync 是我写的一个辅助函数;看起来像这样:

/**
 * Helps load Google APIs asynchronously.
 *
 * @param {string} source
 * @param {string} callbackParam
 * @param {string=} globalName
 * @returns {Promise}
 */
export function loadAsync(source, callbackParam, globalName) {
    return new Promise((resolve,reject) => {
        let callbackFunc = Math.random().toString(36);

        window[callbackFunc] = () => {
            resolve(window[globalName]);
            delete window[callbackFunc];
        };

        let sep = source.includes('?') ? '&' : '?';
        $script(`${source}${sep}${encodeURIComponent(callbackParam)}=${encodeURIComponent(callbackFunc)}`);
    });
}

它使用scriptjs。不幸的是,scriptjs 的回调触发得太早了——谷歌在 client.js 下载后加载了更多的垃圾,所以即使在它“准备好”之后它还没有准备好运行!您必须使用 Google 的 onload 参数。

如果您只是使用 bunch of <script> tags,则不需要所有这些依赖项,但我更喜欢一些异步函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多