Google Calendar API Freebusy JQuery $ .post收到400(错误请求)错误

时间:2015-04-18 08:13:25

标签: javascript jquery google-calendar-api

我是javascript,JQuery和Google API的新手,所以这个问题的答案可能是一个非常简单的事情,我忽略了。我已经在此网站上查看了所有可用的Google Calendar Freebusy问题,但我无法以任何方式使他们的答案适合我的代码。

我正在尝试为html页面编写一个脚本来检查公共日历的freebusy查询。 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)错误。进一步深入了解错误信息会返回"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错误/ json请求我忽略了?提前感谢您的帮助和建议。

1 个答案:

答案 0 :(得分:2)

Google Calendar 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'
})

感谢您的建议!

相关问题