FullCalendar 是一個(gè)流行的 JavaScript 事件日歷庫(kù),可以輕松地將其與后端數(shù)據(jù)進(jìn)行交互
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FullCalendar with Backend Data</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.9.0/main.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.9.0/main.min.js"></script>
</head>
<body>
<div id="calendar"></div>
<script src="app.js"></script>
</body>
</html>
app.js
文件中,初始化 FullCalendar 并配置事件源。這里我們使用一個(gè)名為 fetchEvents
的函數(shù)從后端獲取事件數(shù)據(jù):document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
events: fetchEvents
});
calendar.render();
});
fetchEvents
函數(shù),該函數(shù)負(fù)責(zé)從后端 API 獲取事件數(shù)據(jù)。這里我們使用 Fetch API 發(fā)送請(qǐng)求,你也可以使用其他庫(kù)(如 jQuery 或 Axios)實(shí)現(xiàn)類(lèi)似功能。async function fetchEvents(info, successCallback, failureCallback) {
try {
const response = await fetch('https://your-backend-api.com/events');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const events = await response.json();
successCallback(events);
} catch (error) {
console.error('There was a problem fetching events:', error);
failureCallback(error);
}
}
/events
),該端點(diǎn)返回一個(gè)包含事件數(shù)據(jù)的 JSON 數(shù)組。事件對(duì)象應(yīng)該包含 id
, title
, start
和 end
屬性。例如:[
{
"id": 1,
"title": "Event 1",
"start": "2022-01-01T10:00:00",
"end": "2022-01-01T12:00:00"
},
{
"id": 2,
"title": "Event 2",
"start": "2022-01-02T14:00:00",
"end": "2022-01-02T16:00:00"
}
]
完成以上步驟后,F(xiàn)ullCalendar 將從后端 API 獲取事件數(shù)據(jù)并顯示在日歷中。你還可以根據(jù)需要自定義事件的樣式、行為和交互。更多關(guān)于 FullCalendar 的信息和文檔,請(qǐng)?jiān)L問(wèn)官方網(wǎng)站:https://fullcalendar.io/