我還是 FullCalendar 的新手,我正在嘗試顯示從 mysqli 資料庫中檢索到的事件。我的表結構如下: 表結構 。我的表格內容如下: 表格內容
下面是我用來生成 FullCalendar 的腳本:
<script>
$(document).ready(function(){
$('#calendar').fullCalendar({
editable:true,
header:{
left:'prev, next today',
center:'title',
right:'month, agendaWeek, agendaDay'
},
//events: 'loadCalendarEvents.php'
events: function(start, end, timezone, callback){
$.ajax({
url: 'loadCalendarEvents.php',
dataType: 'json',
data: {
},
success: function(data){
var events = [];
for (var i=0; i<data.length; i ){
events.push({
title: data[i]['class'],
start: data[i]['start_event'],
end: data[i]['end_event'],
});
}
}
});
}
});
});
</script>
下面是添加事件的檔案 (loadCalendarEvents.php):
<?php
include("db.php");//Includes the database file that makes the connection
$timetable = mysqli_query($conn, "SELECT class, start_event, end_event FROM lecturertimetable");//Loading events for the calendar
$myArray = array();
if ($timetable->num_rows > 0) {
// To output the data of each row
while($row = $timetable->fetch_assoc()) {
$myArray[] = $row;
}
}
echo json_encode($myArray);
?>
但是,沒有顯示任何事件,我不確定我做錯了什么。
uj5u.com熱心網友回復:
這是因為您的 HTML 頁面在頁面加載時呈現 FullCalendar javascript。所以那個時候你沒有任何事件。(因為瀏覽器必須向 發出請求loadCalendarEvents.php才能獲取事件。)
您可以通過三種方式解決此問題。
- 為控制器中的事件創建 JSON 物件并作為引數傳遞。
- 發出 AJAX 請求
loadCalendarEvents.php并成功后,將事件加載到日歷中。 - 發出 AJAX 請求
loadCalendarEvents.php并在成功時呈現 fullCalendar。
以下代碼發送 AJAX 呼叫以從loadCalendarEvents.php.
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: 'loadCalendarEvents.php',
dataType: 'json',
data: {
// If you have some data to send to loadCalendarEvents.php
id: 1,
name: "hello"
},
success: function(data) {
var events = [];
for (var i=0; i<data.length; i ){
events.push({
title: data[i]['class'],
start: data[i]['start_event'],
end: data[i]['end_event'],
});
}
//adding the callback
callback(events);
}
});
}
});
uj5u.com熱心網友回復:
我從您問題的原始版本中注意到,您最初只是將資料提要指定為
events: 'loadCalendarEvents.php'
這種方法沒有任何問題——它由 fullCalendar 記錄。每當需要獲取事件時,FullCalendar 都會自動向該 URL 發送 AJAX 請求。
您在該版本中遇到的唯一問題是類、start_event 和 end_event 欄位的命名不正確 - 您需要呼叫它們title,start并end精確匹配fullCalendar 所需的名稱,否則它將無法識別或使用它們,當然沒有可識別時間和描述的事件不能顯示在日歷上。
有兩種可能的修復方法:
只需將您的資料庫列重命名為
title,start和end。使用 PHP 創建一個具有正確命名欄位的陣列:
代碼:
while($row = $timetable->fetch_assoc()) {
$myArray[] = $array(
"title" => $row["class"],
"start" => $row["start_event"],
"end" => $row["end_event"],
);
}
注意您還應該(根據檔案)修改 PHP,以便它注意到fullCalendar 自動附加到請求的start和end引數,并將您的 SQL 查詢限制為僅回傳落在這些日期之間的事件。這樣 fullCalendar 將只提供它實際需要的資料,而不會低效下載(可能)用戶不會查看的多年歷史資料。
PS 如果您剛剛開始使用 fullCalendar,我建議您使用最新的第 5 版,而不是您在這里使用的第 3 版。它具有更多功能,修復了許多錯誤,并且性能有所提高。見https://fullcalendar.io/docs/v5/getting-started
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/362876.html
