详细说明 Rob Van Dam 的答案,这里是一个代码示例(使用 jQuery UI 日期选择器),用于使用 AJAX 获取启用的日期。我使用 AJAX 查询从数据库返回启用日期的 PHP 页面(因为我只想显示我有实际数据的日期)。
这个想法是在每次用户更改月份时执行 AJAX 查询,然后将本月的启用日期存储在一个全局数组 (allowedDates) 中,该数组稍后由 beforeShowDay 使用。
当然,您可以在 beforeShowDay 中进行 AJAX 查询,但是由于 AJAX 查询的数量很大(每个月超过 30 个),这将是非常低效的。
var allowedDates = new Object();
function queryAllowedDates (year, month, id) {
$.ajax({
type: 'GET',
url: 'calendar_days.php',
dataType: 'json',
success: function(response) {
allowedDates[id] = response.allowedDates;
},
data: {year:year,month:month},
async: false
});
}
$("#datepicker1").datepicker({
dateFormat: 'dd.mm.yy',
changeMonth: true,
changeYear: true ,
beforeShow: function (input) {
var currentDate = $(input).datepicker('getDate');
var id = $(input).attr('id');
queryAllowedDates(currentDate.getFullYear(), currentDate.getMonth()+1,id);
},
onChangeMonthYear: function (year, month, inst) {
queryAllowedDates(year, month, inst.input.attr('id'));
},
beforeShowDay: function (day) {
var id = $(this).attr('id');
var date_str = [
day.getFullYear(),
day.getMonth() + 1,
day.getDate()
].join('-');
if (allowedDates[id] != undefined && allowedDates[id][date_str]) {
return [true, 'good_date', 'This date is selectable'];
} else {
return [false, 'bad_date', 'This date is NOT selectable'];
}
}
});
在本例中,PHP 页面返回一个 JSON 数组,其中包含如下内容:
{"allowedDates":{"2008-12-04":1,"2008-12-11":1}}