如何将表单选中的年月传入FullCalendar以展示对应日历?
实现表单年月传递给FullCalendar的方案
1. 后端获取表单提交的年月参数
在search.php中先获取POST提交的年月值,无提交时默认使用当前年月:
<?php $id = $_GET['id']; // 获取选中的年月,默认用当前日期 $selectedYear = isset($_POST['year']) ? $_POST['year'] : date('Y'); $selectedMonth = isset($_POST['month']) ? $_POST['month'] : date('m'); ?>
2. 初始化FullCalendar时指定显示年月
修改FullCalendar初始化代码,添加defaultDate指定默认展示的年月,同时把年月参数传给事件接口,确保只加载对应时段的事件:
$(document).ready(function() { $('#calendar').fullCalendar({ editable: true, // 设置日历默认显示的年月 defaultDate: '<?= $selectedYear ?>-<?= $selectedMonth ?>', // 传递年月参数到事件接口 events: { url: "fetch-event.php?id=<?php echo $id ?>", data: { year: '<?= $selectedYear ?>', month: '<?= $selectedMonth ?>' } }, displayEventTime: false, eventRender: function(event, element, view) { event.allDay = (event.allDay === 'true'); }, }); });
3. 优化表单默认值(可选)
把表单输入框的默认值设为选中的年月,用户提交后能直观看到之前的选择:
<form class="navbar-search" action="search.php?id=<?= $id ?>" method="post"> <div class="row"> <div class="col"> <label for="year">YEAR:</label> <input name="year" value="<?= $selectedYear ?>" class="form-control form-control-user" id="yearpicker" placeholder="Please Choose..." autocomplete="off"> </div> <div class="col"> <label for="month">MONTH :</label> <input name="month" value="<?= $selectedMonth ?>" class="form-control form-control-user" id="monthpicker" placeholder="Please Choose..." autocomplete="off"> </div> </div><br> <button name="search" id="search" type="submit" class="btn btn-primary btn-user btn-block"><i class="fas fa-search fa-sm"></i> SEARCH</button> <hr> </form>
4. 无刷新更新日历(可选,无需页面跳转)
如果不想刷新页面,用AJAX拦截表单提交,动态更新日历:
修改前端JS代码
$(document).ready(function() { // 初始化日历实例 var calendar = $('#calendar').fullCalendar({ editable: true, defaultDate: '<?= date('Y-m') ?>', events: "fetch-event.php?id=<?php echo $id ?>", displayEventTime: false, eventRender: function(event, element, view) { event.allDay = (event.allDay === 'true'); }, }); // 拦截表单提交事件 $('.navbar-search').submit(function(e) { e.preventDefault(); var year = $('#yearpicker').val(); var month = $('#monthpicker').val(); // 跳转到选中的年月 calendar.fullCalendar('gotoDate', year + '-' + month); // 重新加载对应年月的事件 calendar.fullCalendar('removeEvents'); calendar.fullCalendar('addEventSource', { url: "fetch-event.php?id=<?php echo $id ?>", data: { year: year, month: month } }); }); });
后端fetch-event.php处理参数
在事件接口中获取年月参数,过滤返回对应时段的事件:
<?php $id = $_GET['id']; $year = isset($_GET['year']) ? $_GET['year'] : date('Y'); $month = isset($_GET['month']) ? $_GET['month'] : date('m'); // 此处根据year和month从数据库查询对应事件,返回JSON格式数据 $events = array(); // 示例查询逻辑... echo json_encode($events); ?>
内容的提问来源于stack exchange,提问作者Jasmirulnaim
相关产品推荐
相关产品推荐

