Google 日历 API 空闲 JQuery $.post 收到 400(错误请求)错误

Google Calendar API Freebusy JQuery $.post gets 400 (Bad Request) Error

我是javascript、JQuery和GoogleAPI的新手,所以这个问题的答案可能是我忽略的一个非常简单的事情。我已经检查了该网站上所有可用的 Google 日历空闲问题,但我无法设法使他们的答案以任何方式适合我的代码。

我正在尝试为 html 页面编写一个脚本来检查 public 日历的忙/闲查询。 Google 表示 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) 错误。进一步挖掘错误信息 returns a parse error with "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);

我的请求在 Google Explorer "Try It" 中收到了正确的响应,所以我认为它可能是我忽略的 javascript error/json 请求?预先感谢您的帮助和建议。

Google 日历 API Post 请求需要将内容类型指定为 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'
})

感谢您的建议!