首页 > 解决方案 > FullCalendar 不通过 AJAX/JSON 呈现所有事件

问题描述

我一直在搞乱 FullCalendar 一段时间,但我有一个小问题。如果我通过 AJAX/JSON 以正确的格式加载事件,日历只会呈现第一个事件。

所有其他事件都显示在console.log通话中,但日历仅显示第一个事件。文档中的示例事件代码如下:

events: [{
    title: 'My Event',
    start: '2010-01-01',
    url: 'http://google.com/'
  },
  {
    title: 'My Event',
    start: '2010-01-02',
    url: 'http://google.com/'
  }
  // other events here
],

我的代码如下:

events: function(start, end, timezone, callback) {
  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
    }
  });
  $.ajax({
    url: "/tande/fetch_holidays/",
    type: 'POST',
    success: function(data) {
      var events = [];
      $.map(data.holidays, function(value) {
        console.log(value)
        description = value.toString().split('_')[0]
        start_date = value.toString().split('_')[1]
        end_date = value.toString().split('_')[2]
        person = value.toString().split('_')[3]
        events.push({
          title: person,
          start: start_date,
          end: end_date
        });
        callback(events);
        console.log(events);
      })
    },
  })
},

标签: javascriptjsonajaxfullcalendar

解决方案


事件的回调放置得太早了。正确代码如下:

events: function(start, end, timezone, callback) {
  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
    }
  });
  $.ajax({
    url: "/tande/fetch_holidays/",
    type: 'POST',
    success: function(data) {
      var events = [];
      $.map(data.holidays, function(value) {
        console.log(value)
        description = value.toString().split('_')[0]
        start_date = value.toString().split('_')[1]
        end_date = value.toString().split('_')[2]
        person = value.toString().split('_')[3]
        events.push({
          title: person + ' - ' + description,
          start: start_date,
          end: end_date,
        });
      })
      callback(events);
    },
  })
},

推荐阅读