Google JavaScript API 的使用
入門

您可以使用javaScript客戶端庫與Web應(yīng)用程序中的Google API(例如,人物,日歷和云端硬盤)進(jìn)行交互。請(qǐng)按照此頁面上的說明進(jìn)行操作。
如何發(fā)出API請(qǐng)求
有幾種方法可以使用javaScript客戶端庫發(fā)出API請(qǐng)求,但是它們都遵循相同的基本模式:
該應(yīng)用程序加載JavaScript客戶端庫。
應(yīng)用程序使用API 密鑰,OAuth客戶端ID和API發(fā)現(xiàn)文檔初始化庫。
應(yīng)用程序發(fā)送請(qǐng)求并處理響應(yīng)。
以下各節(jié)顯示了使用JavaScript客戶端庫的3種常用方法。
選項(xiàng)1:加載API發(fā)現(xiàn)文檔,然后組合請(qǐng)求。
以下示例假定用戶已經(jīng)登錄。有關(guān)如何登錄用戶的完整示例,請(qǐng)參見完整的auth示例。
function start() {
// 2. Initialize the JavaScript client library.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
// Your API key will be automatically added to the Discovery Document URLs.
'discoveryDocs': ['https://people.googleapis.com/$discovery/rest'],
// clientId and scope are optional if auth is not required.
'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
'scope': 'profile',
}).then(function() {
// 3. Initialize and make the API request.
return gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names'
});
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// 1. Load the JavaScript client library.
gapi.load('client', start);
選項(xiàng)2:使用?gapi.client.request
發(fā)出請(qǐng)求的更一般的方法是使用gapi.client.request。您的應(yīng)用程序不必像第一個(gè)選項(xiàng)那樣加載“發(fā)現(xiàn)文檔”,但是它仍必須設(shè)置API密鑰(并對(duì)某些API進(jìn)行身份驗(yàn)證)。當(dāng)您需要使用此選項(xiàng)手動(dòng)填寫REST參數(shù)時(shí),它可以節(jié)省一個(gè)網(wǎng)絡(luò)請(qǐng)求并減小應(yīng)用程序大小。
function start() {
// 2. Initialize the JavaScript client library.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
// clientId and scope are optional if auth is not required.
'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
'scope': 'profile',
}).then(function() {
// 3. Initialize and make the API request.
return gapi.client.request({
'path': 'https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names',
})
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// 1. Load the JavaScript client library.
gapi.load('client', start);
選項(xiàng)3:使用CORS
Google API支持CORS。如果您的應(yīng)用程序需要進(jìn)行媒體上載和下載,則應(yīng)使用CORS。有關(guān)詳細(xì)信息,請(qǐng)參見CORS支持頁面。
支持的環(huán)境
JavaScript客戶端庫可與Google Apps支持的瀏覽器一起使用,但當(dāng)前不完全支持移動(dòng)瀏覽器。它僅在具有
使用https?(首選)和http協(xié)議提供元素的HTML文檔中起作用。但是,