我是javascript,JQuery和Google API的新手,所以这个问题的答案可能是我忽略的非常简单的事情。我已经检查了这个网站上所有可用的谷歌日历忙于问题,但我无法让他们的答案以任何方式适合我的代码。
我正在尝试为检查公共日历的 freebusy 查询的 html 页面编写脚本。谷歌表示HTTP请求应该是
POST https://www.googleapis.com/calendar/v3/freeBusy
请求正文为
{
"timeMin": datetime,
"timeMax": datetime,
"timeZone": string,
"groupExpansionMax": integer,
"calendarExpansionMax": integer,
"items": [
{
"id": string
}
]
}
我当前的 html 页面包括最新的 jquery 库和我正在编写的脚本。调用页面上的脚本会导致Failed to load resource: the server responded with a status of 400 (Bad Request)
错误。进一步挖掘错误信息会返回解析错误,并显示"This API does not support parsing form-encoded input."
我的脚本如下所示:
(function ($) {
$.GoogleCalendarFreebusy = function (options) {
var defaults = {
apiKey: '[projectkey]',
getID: '[id]@group.calendar.google.com',
element: '#div'
};
options = $.extend(defaults, options);
$.post('https://www.googleapis.com/calendar/v3/freeBusy?key=' + options.apiKey,
{"items":[{"id": getID }],"timeMin":"2015-04-10T14:15:00.000Z","timeMax":"2015-04-20T23:30:00.000Z"}, "null", "json")
.done(function(data) {
loaded(data);
});
function loaded(data) {
var status = data.calendars[getID].busy;
console.log(status);
if(status.length !== 0 ) {
for(var i = 0; i < status.length; i++) {
var statusEntry = status[i];
var startTime = statusEntry.start;
var endTime = statusEntry.end;
}
var now = new Date().toISOString();
var element = options.element ;
var name = element.substr(1);
if (now > startTime && now < endTime){
$(options.element).append( 'Available!');
}
else {
$(options.element).append( 'Unavailable!');
}
} else {
$(options.element).append('Unavailable!');
}
}
};
})(jQuery);
我的请求在谷歌资源管理器"尝试"中收到正确的响应,所以我认为这可能是我忽略的javascript错误/json请求?提前感谢您的帮助和建议。
Google 日历 API 发布请求需要将内容类型指定为 JSON,以避免上述错误。将 POST 作为指定了 contentType 的 AJAX 请求进行处理可解决此错误。
$.ajax({
url: 'https://www.googleapis.com/calendar/v3/freeBusy?key=' + options.apiKey,
type: 'POST',
data: '{"items":[{"id": "[id]@group.calendar.google.com"}], "timeMin": "2015-04-10T14:15:00.000Z", "timeMax": "2015-04-20T23:30:00.000Z"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: 'null'
})
感谢您的建议!