小编典典

在jQuery UI datepicker中仅选择特定日期(日期列表来自AJAX)

ajax

在这里,我发送电影ID并获取可用的日期,我想将其设置为日历。但它不起作用,并且会禁用所有日期。从PHP返回日期字符串。日期字符串正确到来,但是日历不起作用。请帮忙。

日期字符串示例

"28-02-2012","29-02-2012","01-03-2012","02-03-2012","03-03-2012","04-03-2012","05-03-2012","06-03-2012","07-03-2012","08-03-2012","09-03-2012","28-02-2012","29-02-2012","01-03-2012","02-03-2012","03-03-2012","04-03-2012","05-03-2012","06-03-2012","07-03-2012","08-03-2012","09-03-2012"

jQuery.post('index.php', {
  'option': 'com_movie',
  'controller': 'reservation',
  'task': 'datelist',
  'format': 'raw',
  'mid': movieid
}, function(result) {
  var onlydates = result.split(',');
  jQuery("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    showOn: "button",
    buttonImage: "<?php echo IMAGES_LINK.'calendar.png';?>",
    buttonImageOnly: true,
    beforeShowDay: function(date) {
      dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
      console.log(dmy + ' : ' + (jQuery.inArray(dmy, onlydates)));
      if (jQuery.inArray(dmy, onlydates) != -1) {
        return [true, "", "Available"];
      } else {
        return [false, "", "unAvailable"];
      }
    }
  });
  return;
});

阅读 255

收藏
2020-07-26

共1个答案

小编典典

  • 仅初始化一次数据选择器;告诉它从全局数组中获取有效日期
  • 使用数组文字初始化全局数组,必要时通过AJAX更新
  • .datepicker("refresh")每当禁用/启用日期更改时(即当您通过AJAX获得新结果时)都调用该方法
  • 您的代码未在日期中添加前导零,因此$.inArray无法按预期工作

var datelist = []; // initialize empty array

$("#datepicker").datepicker({
    beforeShowDay: function(d) {
        // normalize the date for searching in array
        var dmy = "";
        dmy += ("00" + d.getDate()).slice(-2) + "-";
        dmy += ("00" + (d.getMonth() + 1)).slice(-2) + "-";
        dmy += d.getFullYear();
        return [$.inArray(dmy, datelist) >= 0 ? true : false, ""];
    }
});

$("#button").click(function() {
    datelist = []; // empty the array
    $.post("/echo/html/", {
        // parameters here
    }, function() {
        var result = "28-02-2012,29-02-2012,01-03-2012,02-03-2012,03-03-2012,04-03-2012,05-03-2012,06-03-2012,07-03-2012,08-03-2012,09-03-2012,28-02-2012,29-02-2012,01-03-2012,02-03-2012,03-03-2012,04-03-2012,05-03-2012,06-03-2012,07-03-2012,08-03-2012,09-03-2012"; // dummy result
        datelist = result.split(","); // populate the array
        $("#datepicker").datepicker("refresh"); // tell datepicker that it needs to draw itself again
    });

在这里演示

2020-07-26