You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中FullCalendar遇JSON解析失败错误,求排查与解决方案

Laravel集成FullCalendar遇到JSON解析失败错误及事件插入实现

问题描述

在Laravel项目中集成FullCalendar时,出现Error: Failure parsing JSON错误,相关代码如下:

Blade文件的JavaScript日历配置:

events: "/fullcalender",

控制器代码:

public function index(Request $request)
{
    if($request->ajax()) {
         $data = Event::whereDate('start', '>=', $request->start)
                   ->whereDate('end',   '<=', $request->end)
                   ->get(['id', 'title', 'start', 'end']);

         return response()->json($data);
    }

    return view('fullcalender');
}

请问该错误的原因是什么?以及如何正确实现日历事件的插入?


错误原因分析

1. 路由配置问题

  • 检查/fullcalender路由是否正确映射到目标控制器方法,确保请求方法为GET(FullCalendar默认以GET方式拉取事件数据)。
  • 注意路由拼写:fullcalender是否为笔误(正确拼写通常为fullcalendar),拼写错误会导致请求返回404 HTML页面,而非合法JSON,直接触发解析失败。

2. JSON输出异常

  • 额外输出干扰:如果控制器方法执行前存在echo、dd()等输出,或者视图模板有多余的HTML/空格,会导致返回内容不是纯JSON,破坏JSON结构。
  • 日期格式不兼容:若Event模型的start/end字段是Carbon实例,Laravel默认会转为ISO格式字符串(符合FullCalendar要求);但如果是自定义日期格式,可能转JSON时出现格式错误,无法被FullCalendar识别。

3. 查询逻辑问题

  • whereDate仅提取日期部分比较,但FullCalendar发送的start/end是带时间的ISO字符串,若数据库字段为datetime类型,可能导致查询结果不符合预期,但空数组属于合法JSON,一般不会触发解析错误,除非伴随其他输出异常。

事件插入的正确实现步骤

1. 前端添加事件提交表单

在Blade视图中添加事件创建表单(示例用模态框):

<div id="eventModal" class="modal">
  <div class="modal-content">
    <h4>添加新事件</h4>
    <form id="eventForm">
      <div class="input-field">
        <input type="text" id="title" name="title" required>
        <label for="title">事件标题</label>
      </div>
      <div class="input-field">
        <input type="datetime-local" id="start" name="start" required>
      </div>
      <div class="input-field">
        <input type="datetime-local" id="end" name="end" required>
      </div>
      <button type="submit" class="btn">保存事件</button>
    </form>
  </div>
</div>

2. 前端AJAX提交逻辑

在日历初始化的JS代码中,添加表单提交的AJAX处理:

// 先定义日历实例(确保已初始化FullCalendar)
const calendar = new FullCalendar.Calendar(document.getElementById('calendar'), {
  // 原有配置...
  events: "/fullcalendar" // 修正路由拼写
});
calendar.render();

// 表单提交处理
document.getElementById('eventForm').addEventListener('submit', function(e) {
  e.preventDefault();
  
  const formData = new FormData(this);
  
  fetch('/fullcalendar/events/store', {
    method: 'POST',
    headers: {
      'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(Object.fromEntries(formData))
  })
  .then(response => response.json())
  .then(data => {
    if(data.success) {
      // 直接添加事件到日历
      calendar.addEvent({
        id: data.event.id,
        title: data.event.title,
        start: data.event.start,
        end: data.event.end
      });
      // 关闭模态框
      document.getElementById('eventModal').style.display = 'none';
    }
  })
  .catch(error => console.error('添加事件失败:', error));
});

3. 后端路由与控制器处理

在routes/web.php添加POST路由:

Route::post('/fullcalendar/events/store', [FullCalendarController::class, 'store']);
// 同时修正原有路由的拼写
Route::get('/fullcalendar', [FullCalendarController::class, 'index']);

在控制器中添加store方法:

use App\Models\Event;
use Illuminate\Http\Request;

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|string',
        'start' => 'required|date',
        'end' => 'required|date|after_or_equal:start'
    ]);

    $event = Event::create([
        'title' => $request->title,
        'start' => $request->start,
        'end' => $request->end
    ]);

    return response()->json([
        'success' => true,
        'event' => $event
    ]);
}

4. 配置模型可填充字段

在Event模型中设置允许批量赋值的字段:

protected $fillable = ['title', 'start', 'end'];

内容的提问来源于stack exchange,提问作者Amedeo De Longis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:07:42