尝试使用Java Script从Google API显示日历列表

时间:2015-04-30 17:19:42

标签: javascript ajax api calendar

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

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

谢谢!

2 个答案:

答案 0 :(得分:7)

要获得基本工作模型,您可以按照calendar API site

上的快速入门示例进行操作

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

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

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

答案 1 :(得分:1)

以下是我刚写的一些代码:

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,则不需要所有这些依赖项,但我更喜欢一些异步函数。