【问题标题】:fullCalendar events from ajax response not loading来自ajax响应的fullCalendar事件未加载
【发布时间】:2017-08-29 02:06:53
【问题描述】:

关于 ajax 和 fullCalendar 的另一个问题。我已经阅读并尝试了之前建议的修复,但都无济于事。我无法将 JSON 事件加载到 fullCalendar。我究竟做错了什么?

$.ajax 调用正在工作并返回值。 JSON 有一个父元素,日历数组数据实际上在 jsondata.message 中。下面代码中的 JSON.stringify 是我各种实验的一部分。

我最初尝试将 fullCalendar eventSource 与内置的 ajax 检索一起使用。我隔离了代码,以为我遇到了呼叫/通信问题。

我已经尝试过 [jsondata.message] 并且只是 jsondata.message。我尝试将 JSON 数据解析为标准数组并将该数组传递给事件项。除了复制响应并将其粘贴到事件中之外,我什么也做不了:双引号内的元素有效。

  1. ajax 调用有效并返回数据。
  2. 因为我可以将 ajax 响应中的数据复制/粘贴到代码中并加载事件,所以它不是数据的格式。

加载事件是否有限制?我正在尝试加载大约 4800 个事件。

AJAX 调用:

$.ajax({
    url: "/appointment/ajax_get_available_records",
    type: "POST",
    data:{
        startdate: start.format("YYYY-MM-DD 00:00:01"),
        enddate: end.format("YYYY-MM-DD 23:59:59"),
        userid:<?= $doctor->user_id?>
    },
    error: function() {
        $('#errormsg').html("<p class='alert alert-danger'>There was an error while fetching calendar events!</p>'");
    },
    success: function(jsondata, status, xhr){
            $('#calendar').fullCalendar({
                events: [JSON.stringify(jsondata.message)],
                color: 'green',
                textColor: 'white' 
            });             
    },
    dataType: "json" 
});

响应标头

Cache-Control:no-transform,public,max-age=300,s-maxage=900
Content-Length:104282
Content-Type:application/json
Date:Tue, 04 Apr 2017 02:40:50 GMT
Server:Microsoft-IIS/10.0
X-Powered-By:ASP.NET

** 部分 AJAX 响应**

{"status":true,
"message":[{
            "doctor_user_id":"636",
            "title":"available",
            "start":"2017-04-03T19:10:00",
            "end":"2017-04-03T19:19:59",
            "clinic_id":"10",
            "clinic_location_id":"0"
           },
           {
            "doctor_user_id":"636",
            "title":"available",
            "start":"2017-04-03T19:20:00",
            "end":"2017-04-03T19:29:59",
            "clinic_id":"10",
            "clinic_location_id":"0"
           },
---- omitted  ----

服务器 php 7.0/MySQL 型号:

    function get_available_dates_in_range($user_id, $start_datetime = null , $end_datetime = null)
    {
        $startrange = date('Y-m-01 H:i:s',strtotime($start_datetime));
        $endrange = date('Y-m-d 23:59:59',strtotime($end_datetime));
    if($endrange == NULL) {
        $end_datetime = date_add($startrange,date_interval_create_from_date_string("INTERVAL 2 MONTHS")); 
        $endrange = date("Y-m-01 00:00:00",$end_datetime);
    }

    $this->db->select(
        "doctor_user_id, 
        status as `title`, 
        DATE_FORMAT(datetime,'%Y-%m-%dT%H:%i:%s') as `start`, 
        DATE_FORMAT(date_add(datetime, Interval 599 SECOND),'%Y-%m-%dT%H:%i:%s') as end, 
        clinic_id, 
        clinic_location_id ");
    $this->db->where('doctor_user_id', $user_id);
    $this->db->where('datetime >=', mysql_user_to_gmt_date($start_datetime));
    $this->db->where('datetime <=', mysql_user_to_gmt_date($end_datetime));
    $this->db->where('status', 'available');
    $this->db->order_by('datetime ASC');
    $query = $this->db->get('schedule_records');
    return $query;  
}

Codeigniter 3.1.4 控制器:

....

$query = $this->appointment_model->get_available_dates_in_range($userid, $startdate, $enddate);
$this->json_response($query->result_array());

编码并返回 JSON 函数

function json_response($message = null, $code = 200) {
    // clear the old headers
    header_remove();
    // set the actual code
    http_response_code($code);
    // set the header to make sure cache is forced
    header("Cache-Control: no-transform,public,max-age=300,s-maxage=900");
    // treat this as json
    header('Content-Type: application/json');
    $status = array(
        200 => '200 OK',
        400 => '400 Bad Request',
        422 => 'Unprocessable Entity',
        500 => '500 Internal Server Error'
        );
    // ok, validation error, or failure
    header('Status: '.$status[$code]);
    // return the encoded json
    echo json_encode(array(
        'status' => $code < 300, // success or not?
        'message' => $message
        ));
}

【问题讨论】:

    标签: php mysql ajax fullcalendar


    【解决方案1】:
    events: [JSON.stringify(jsondata.message)] 
    

    对我来说看起来很狡猾。您只是在创建一个包含一个元素的数组,其中包含一个巨大的字符串(因为 JSON.stringify 会按照它所说的去做,并将您的对象变成一个字符串,而不再是一个可用的对象。它用于在屏幕上显示您的 JSON ,不用于处理)。试试

    events: jsondata.message
    

    相反。

    虽然,整个代码确实是错误的方式 - 这样做你将不得不在 fullCalendar 视图更改(即用户按下下一个/上一个)时自己处理数据更新。如果您使用 fullCalendar 的“事件即函数”,您可以使用自己的 ajax 代码,但在需要获取新事件时让 fullCalendar 再次处理查询服务器。

    有关更多详细信息和示例,请参阅https://fullcalendar.io/docs/event_data/events_function,但我会这样做:

    $('#calendar').fullCalendar({
      events: function(start, end, timezone, callback) {
        $.ajax({
          url: "/appointment/ajax_get_available_records",
          type: "POST",
          data:{
            startdate: start.format("YYYY-MM-DD 00:00:01"),
            enddate: end.format("YYYY-MM-DD 23:59:59"),
            userid:<?= $doctor->user_id?>
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#errormsg').html("<p class='alert alert-danger'>There was an error while fetching calendar events!</p>'");
            console.log("Error fetching events: " + textStatus + errorThrown); //log the error for debugging
            callback([]); //no data was retrieved, so send an empty array of events to fullCalendar
          },
          success: function(jsondata, status, xhr){
            callback(jsondata.message); //sends the events to fullCalendar
          },
          dataType: "json" 
        });
      },
      color: 'green',
      textColor: 'white' 
    });
    

    这样,如果用户按下下一个或上一个,或以其他方式更改正在显示的视图或日期范围,fullCalendar 将自动调用“事件”中定义的函数并使用正确的开始/结束日期并将事件提取到日历中.

    【讨论】:

    • 感谢您的回复。你的建议是我最初编码的方式。不幸的是,MySQL 调用大约需要 1.3-1.8 秒的往返时间,这使它成为一种不愉快的 UX 体验。 stringify 是我调试工作的一部分,试图猜测我的事件发生了什么。这同样适用于将 ajax 调用从 eventSources 移出到单独的调用中。
    • 我建议您修复您的 SQL 查询和/或 PHP。获取少量这样的事件应该不会花费太长时间,除非您将数百个事件添加到单个日历视图中?您还可以通过在 ajax 运行时在页面某处添加“正在加载...请稍候”微调器来帮助用户体验。如果用户意识到数据正在传输中并且没有崩溃,他们更有可能耐心等待。而且......它看起来不像你有,但请确保 ajax 没有以同步模式运行,因为这确实会导致糟糕的用户体验。
    • 同意微调器/叠加层已经存在。但我们正在加载 30 天 ~ 4800 个事件。以前的版本逐页加载数据,中间有一个往返。问题实际上是糟糕的架构,但它不是我的,它是基础的。这是一个过渡版本,我们必须使用旧的数据库模式。当我们放弃 Codeigniter 时,ng2 版本将会重新设计。
    • 如果您有这么多事件,那么实际上我会说
    • 你在每一点上都是对的。在 listDay 以外的任何视图上有效查看的插槽太多。所以,我重构了两个完整的日历。日历“A”仅将 1 周的事件显示为 listDay。如果有任何可用的时间段,日历“B”可以被视为基本周或月,每天只有一个事件。单击 Cal“B”上的事件将用户定位在 Cal“A”的 listDay 视图中,其中包含详细的时间段。它是一个 kluge,但它的速度很快,并且提供了良好的用户体验。
    【解决方案2】:

    昨晚我找到了自己的答案。显然我的 JSON 数据已被缓存。清除我的浏览器缓存并重新启动服务器解决了我的问题(在删除我为测试而放入的 JSON.stringify 之后。

    【讨论】:

      猜你喜欢
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多