gpt4 book ai didi

javascript - 将事件加载到 FullCalendar

转载 作者:行者123 更新时间:2023-11-30 07:33:12 24 4
gpt4 key购买 nike

到目前为止,我一直在执行同步 ajax 调用以从数据库中获取事件,然后使用从 ajax (解决方案 1) 返回的变量初始化日历。

我读到过同步调用通常被认为是不好的,因为它会卡住浏览器,所以我尝试了另一种选择,将 ajax 调用直接放在 FullCalendar 日历初始化的事件数组中(解决方案 2)。这在第一次加载时提供了很好的体验,因为浏览器不会由于异步 ajax 而被锁定,并且您可以在日历建立时看到它。

然而,这有一个缺点,每次您更改 View 时,它都会重新呈现事件,与第一个事件相比,给用户带来不那么流畅的体验。以下是我目前尝试过的两种解决方案的代码:

解决方案一:

$(document).ready(function(){
$.ajax({
url: 'script.php',
type: 'POST',
async: false,
success: function(response){
json_events = response;

}
});
$('#calendar').fullCalendar({
events: JSON.parse(JSON.stringify(json_events)),
});

});

解决方案 2:

 $(document).ready(function(){
$('#calendar').fullCalendar({

events: {
url: 'script.php',
type: 'POST',
success : function(response){
}
}
});

});

这个“问题”还有其他解决方案吗?不对,我更喜欢解决方案 1,因为您不必在使用日历时处理事件的重新呈现,但最好不要在加载页面时进行初始卡住。

编辑:脚本.php

$events = array();
$query = mysqli_query($link, "SELECT * FROM calendar");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$e = array();
$e['id'] = $fetch['id'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
array_push($events, $e);
}
echo json_encode($events);

这行得通吗? (对于评论中的戴森)

  events: {
url: 'script2.php',
type: 'POST',
data : {
calendar_id : calendarId
},
success : function(response){
}
}

脚本2.php

$calend_id = $_POST['calendar_id'];
$start = $_POST['start'];
$end = $_POST['end'];
$events = array();
$query = mysqli_query($link, "SELECT startdate,enddate,id FROM calendar WHERE calendar_id = '$calend_id' AND startdate >= '$start' AND enddate <= '$end'");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$e = array();
$e['id'] = $fetch['id'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
array_push($events, $e);
}
echo json_encode($events);

最佳答案

FullCalendar 确实希望您只加载当前 View 所需的事件。这意味着您不必预先加载所有您的事件。想一想,一旦您的软件运行了几年,“所有事件”可能会相当大,并且会减慢日历的加载速度。此外,您还必须考虑用户突然想要查看 3 年前的日历的可能性有多大?这可能是一种边缘情况,因此您不需要立即处理这些事件。

FullCalendar 提供了一种非常简洁的方法来自动执行此操作。请参阅此链接 https://fullcalendar.io/docs/event_data/events_json_feed/

基本上,您只需将 PHP 端点指定为“事件”URL,只要您遵守该链接中指定的结构,它就会在用户更改日期范围和/或显示的 View 时自动下载正确的事件.

因此,在您的日历配置中:

events: "script.php"

就这么简单! FullCalendar 将自动传递两个字段——“开始”和“结束”作为获取事件的日期。所以在你的 PHP 中,你需要这样的东西:

$events = array();
$start = $_GET["start"];
$end = $_GET["end"];
//code to build a query with a WHERE clause specifying the start/end dates
//...
//and finally echo the resulting events
echo json_encode($events);

除非网络延迟对您来说是个大问题,否则最好只在需要时小批量下载事件。此外,默认情况下有一个日历选项集:lazyFetching: true,它会尽量减少所需的 ajax 调用次数 - 请参阅 https://fullcalendar.io/docs/event_data/lazyFetching/详细了解其工作原理。

如果您担心加载事件时的用户体验,您可以处理“正在加载”回调,这样您就可以添加类似“正在加载”微调器或其他东西的东西来向用户表明他们只需要等待几秒钟,让事件出现。参见 https://fullcalendar.io/docs/event_data/loading/再次了解更多详情。

关于javascript - 将事件加载到 FullCalendar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43863997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com