FullCalendar-我无法检索日历中的事件

如何解决FullCalendar-我无法检索日历中的事件

我在“ / index” URL上有json格式的事件。我希望能够检索它们以便在日历上显示它们。我遵循了这封信的官方教程,但不幸的是我还是做不到,这是我的文件:

calendar.js

$(function () {
    'use strict'

    // Initialize fullCalendar
    $('#calendar').fullCalendar({
        height: 'parent',locale: 'fr',header: {
            left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay,listWeek'
        },navLinks: true,selectable: true,selectLongPressDelay: 100,editable: true,nowIndicator: true,defaultView: 'listMonth',views: {
            agenda: {
                columnHeaderHtml: function (mom) {
                    return '<span>' + mom.format('ddd') + '</span>' +
                        '<span>' + mom.format('DD') + '</span>';
                }
            },day: {
                columnHeader: false
            },listMonth: {
                listDayFormat: 'ddd DD',listDayAltFormat: false
            },listWeek: {
                listDayFormat: 'ddd DD',agendaThreeDay: {
                type: 'agenda',duration: {
                    days: 3
                },titleFormat: 'MMMM YYYY'
            }
        },events: "/index",eventAfterAllRender: function (view) {
            if (view.name === 'listMonth' || view.name === 'listWeek') {
                var dates = view.el.find('.fc-list-heading-main');
                dates.each(function () {
                    var text = $(this).text().split(' ');
                    var now = moment().format('DD');

                    $(this).html(text[0] + '<span>' + text[1] + '</span>');
                    if (now === text[1]) {
                        $(this).addClass('now');
                    }
                });
            }

            console.log(view.el);
        },eventRender: function (event,element) {

            if (event.description) {
                element.find('.fc-list-item-title').append('<span class="fc-desc">' + event.description + '</span>');
                element.find('.fc-content').append('<span class="fc-desc">' + event.description + '</span>');
            }

            var eBorderColor = (event.source.borderColor) ? event.source.borderColor : event.borderColor;
            element.find('.fc-list-item-time').css({
                color: eBorderColor,borderColor: eBorderColor
            });

            element.find('.fc-list-item-title').css({
                borderColor: eBorderColor
            });

            element.css('borderLeftColor',eBorderColor);
        },});

    var calendar = $('#calendar').fullCalendar('getCalendar');

    // change view to week when in tablet
    if (window.matchMedia('(min-width: 576px)').matches) {
        calendar.changeView('agendaWeek');
    }

    // change view to month when in desktop
    if (window.matchMedia('(min-width: 992px)').matches) {
        calendar.changeView('month');
    }

    // change view based in viewport width when resize is detected
    calendar.option('windowResize',function (view) {
        if (view.name === 'listWeek') {
            if (window.matchMedia('(min-width: 992px)').matches) {
                calendar.changeView('month');
            } else {
                calendar.changeView('listWeek');
            }
        }
    });

    // Display calendar event modal
    calendar.on('eventClick',function (calEvent,jsEvent,view) {

        var modal = $('#modalCalendarEvent');

        modal.modal('show');
        modal.find('.event-title').text(calEvent.title);

        if (calEvent.description) {
            modal.find('.event-desc').text(calEvent.description);
            modal.find('.event-desc').prev().removeClass('d-none');
        } else {
            modal.find('.event-desc').text('');
            modal.find('.event-desc').prev().addClass('d-none');
        }

        modal.find('.event-start-date').text(moment(calEvent.start).format('LLL'));
        modal.find('.event-end-date').text(moment(calEvent.end).format('LLL'));

        //styling
        modal.find('.modal-header').css('backgroundColor',(calEvent.source.borderColor) ? calEvent.source.borderColor : calEvent.borderColor);
    });


    //display current date
    var dateNow = calendar.getDate();
    calendar.option('select',function (startDate,endDate) {
        $('#modalCreateEvent').modal('show');
        $('#eventStartDate').val(startDate.format('LL'));
        $('#eventEndDate').val(endDate.format('LL'));

        $('#eventStartTime').val('07:00:00').trigger('change');
        $('#eventEndTime').val('10:00:00').trigger('change');
    });

    $('.select2-modal').select2({
        minimumResultsForSearch: Infinity,dropdownCssClass: 'select2-dropdown-modal',});

    $('.calendar-add').on('click',function (e) {
        e.preventDefault()

        $('#modalCreateEvent').modal('show');
    });


})

web.php(laravel)

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


/* Courses Routes */
Route::post('admin/calendar','CoursesController@store')->name('courses.store');
Route::get('index','CoursesController@index');

我对“ / index”进行请求时的结果,这是结果:

{
        "backgroundColor": "rgba(91,71,251,.2)","borderColor": "#5b47fb","events": [{
            "start": "2020-10-07T07:00:00","end": "2020-10-07T10:00:00","title": "statistiques","description": "drink Coffee"
        }]
};

类似结果的屏幕截图:

enter image description here

这里是管理所有内容的“课程控制器”类

<?php
namespace App\Http\Controllers;

use App\Courses;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\CourseResource;

class CoursesController extends Controller
{
     /**
     * Create a new controller instance.
     *
     * @return void
     */
    
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * retrieve the data from the "courses" table
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $course = DB::select('select * from courses where universityReference = ?',[Auth::user()->universityReference]);

        //let's select the first line
        $data = [
            "backgroundColor" => $course[0]->backgroundColor,"borderColor" => $course[0]->borderColor,"events" => [unserialize($course[0]->events)]
        ];

        return array($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * transform the raw data collected,in order to properly format them for recording
     * 
     */

    public function composeCourseData($arg)
    {
        //convert dates into ISODATE format ('Y-m-d')
        $convertStartDate = date('Y-m-d',strtotime(str_replace('-','/',$arg->input('startDate'))));
        $convertEndDate = date('Y-m-d',$arg->input('endDate'))));
        
        //convert times into ISOTIME format (H:M:S)
        $convertStartTime = strftime('%H:%M:%S',strtotime($arg->input('startTime')));
        $convertEndTime = strftime('%H:%M:%S',strtotime($arg->input('endTime')));

        //final datetime output
        $outputStartDate = "".$convertStartDate."T".$convertStartTime."" ;
        $outputEndDate = "".$convertEndDate."T".$convertEndTime."" ;

        //array to store course basic informations
        $courseData = array(
            'courseToken' => Str::random(23,'alphaNum'),'creatorReference' => Auth::user()->reference,'professorName' => $arg->input('professorName'),'location' => $arg->input('location'),'start' => $outputStartDate,'end' => $outputEndDate,'title' => $arg->input('subject'),'description' => "".$arg->input('type')." '".$arg->input('subject')."' en ".$arg->input('location')." du ".$arg->input('professorName')." avec les etudiants de ".$arg->input('studyYear')." annee (".$arg->input('faculty').")",);

         //serialize course data before saving in db;
         return serialize($courseData);
    }
    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        
        //Validate informations
        /*$course = request()->validate([
            /*'professorName'=>'required|string'
            'subject'=> 'string|required','location'=>'required','start'=>'required','end'=>'required','description'=>'string'
         ]);*/


         /* switch to determine the type of event (course,homework,tutorials or exams)
         * in order to assign a color
         * */
            switch ($request->input('type')) {
                case 'examens':
                    $ok = Courses::create([
                        //think about how to externalize this part of the code which is repeated almost 4 times
                        'universityReference' => Auth::user()->universityReference,'type' => $arg->input('type'),'faculty' => $arg->input('faculty'),'studyYear' => $arg->input('studyYear'),//green
                        'backgroundColor' => 'rgba(16,183,89,.25)','borderColor' => '#10b759','events' => $this->composeCourseData($request)
                    ]);
                    break;

                case 'TD':
                    Courses::create([
                        //orange
                        'universityReference' => Auth::user()->universityReference,'type' => $request->input('type'),'faculty' => $request->input('faculty'),'studyYear' => $request->input('studyYear'),'backgroundColor' => 'rgba(253,126,20,'borderColor' => '#fd7e14','events' => $this->composeCourseData($request)
                    ]);
                    break;
                
                case 'devoirs':
                    Courses::create([
                        //pink
                        'universityReference' => Auth::user()->universityReference,'backgroundColor' => 'rgba(241,117,'borderColor' => '#f10075','events' => $this->composeCourseData($request)
                    ]);
                    break;

                default:
                    Courses::create([
                        //purple
                        'universityReference' => Auth::user()->universityReference,'backgroundColor' => 'rgba(91,.2)','borderColor' => '#5b47fb','events' => $this->composeCourseData($request)
                    ]);
                    break;
            }

        return redirect()->route('admin.app.calendar');
    
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,Courses $course)
    {
       
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Courses $course)
    {
        $course->delete();
        return response('Course removed successfuly !',Response::HTTP_NO_CONTENT);
    }

}

我知道这不是标准的用途,但是我想以这种格式检索事件吗?

因为:我将所有类型($ request-> input('type')与(检查或TD ..)类型相同的事件保存在单个“事件”数组中,并使用精确的backgroundColor和borderColor进行存储每次尝试保存相同“类型”的事件时,我只需通过编辑“事件”数组来修改相应的行。

 {  
    backgroundColor: 'rgba(253,borderColor: '#fd7e14',events: [{
            id: '16',start: '2020-10-07T07:00:00',end: '2020-10-07T07:00:00',title: 'My Rest Day'
        },{
            id: '17',end: '2020-10-08T11:00:00',title: 'My Rest Day'
        }
    ]
 }

解决方法

您的PHP代码生成的JSON结构与fullCalendar不兼容。它必须是事件的简单数组,周围没有外部结构。

例如它应该输出这种结构

[
  { 
    "start": "2020-10-07T07:00:00","end": "2020-10-07T10:00:00","title": "statistiques","description": "drink Coffee"         
  }
] 

仅。

为此,您需要按如下所示修改PHP。我仍然包括了背景和边框颜色,但是需要分别将它们附加到每个事件对象上:

public function index()
{
    $course = DB::select('select * from courses where universityReference = ?',[Auth::user()->universityReference]);

    //let's select the first line
    $data = [unserialize($course[0]->events)];

    foreach ($data as $item)
    {
       $item["backgroundColor"] = $course[0]->backgroundColor;
       $item["borderColor"] = $course[0]->borderColor;
    }

    return $data;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-