2015-04-30 42 views
1

我有一些麻煩,可以通過Google API顯示Google日曆中的可訪問日曆列表。我使用JavaScript和AJAX。嘗試使用Java腳本從Google API顯示日曆列表

我需要使用哪些方法? 我發現只有事件的相關方法,但沒有顯示日曆的描述。

謝謝!

+0

你有什麼樣的代碼你到目前爲止嘗試過嗎? – Kmeixner

回答

5

獲得一個基本的工作模式可以遵循的calendar API site

快速入門示例中的例子有一個函數調用listUpcomingEvents()來獲取對「主」日曆事件。要獲取日曆列表使用下面的方法:

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

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

你在哪裏找到有關'gapi.client.calendar.calendarList.list'的文檔? [參考文檔](https://developers.google.com/google-apps/calendar/v3/reference/calendarList/list)僅顯示Java,Python,PHP和Ruby以及[JS文檔](https:// developers.google.com/api-client-library/javascript/reference/referencedocs)沒有提及日曆。 – mpen

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,則不需要所有這些依賴項,但我更喜歡使用一些異步函數。