如何在月份更改后的UI datepicker中启用日期?

时间:2010-11-14 02:10:13

标签: jquery ajax jquery-ui datepicker

  

原始问题链接:   Help! How to make days enabled in UI datepicker after month change?

首先,Nick Craver的解决方案很精彩。但是我遇到了另一个问题:

Nick Craver的日期源来自js变量xml,但我的日期源来自xml文件。所以我得到了相同的日期结果,但是datepicker没有按照我的方式显示。

Nick Craver的代码:

var xml = '<?xml version="1.0" encoding="utf-8"?><users><user id="126"><name>john</name><watchHistory><whMonthRecords month="2010-10"><whDateList month="2010-10"><date>01</date><date>05</date><date>21</date></whDateList></whMonthRecords><whMonthRecords month="2010-11"><whDateList month="2010-11"><date>01</date><date>05</date><date>06</date><date>07</date><date>08</date><date>09</date><date>12</date><date>13</date><date>14</date><date>16</date><date>18</date><date>19</date><date>21</date><date>22</date><date>23</date><date>24</date><date>25</date><date>26</date><date>29</date></whDateList></whMonthRecords></watchHistory></user></users>';

var daysWithRecords = [];

function getDays(year,month){
  initDaysArray( $(xml) , year ,  month );
}

我希望它是:[没有工作]

var daysWithRecords = [];

function getDays(year,month){
 $.ajax({
  type: "GET",
  url: "users.xml",
  dataType: "xml",
  success:function(data){ 
                initDaysArray($(data) , year ,  month );
            }
  });

功能initDaysArray()

function initDaysArray( $xml , year , month ){
 var dateToFind = year+'-'+month;

 daysWithRecords = $xml.find('user[id="126"] whDateList[month="'+dateToFind+'"] date').map(function() {
  return dateToFind +"-"+ $(this).text();
    }).get();

 for(i = 0; i < daysWithRecords.length; i++){
        console.log(daysWithRecords[i]);
 }
}

我通过Firebug进行测试。似乎按以下顺序调用函数:

first call:   getDays()  // being called from onChangeMonthYear
second call:  checkAvailability()  //  being called from beforeShowDay
third call:   ajax inside getDays() // being called inside getDays()
final call:   initDaysArray()  // being called inside ajax success of getDays() 

所以,initDaysArray[]

内的checkAvailability() 始终为空

[我的解决方案]

我找到了解决这个问题的方法:

在ajax读取xml文件后使用datepicker's method "refresh"重绘日期选择器

function getDays(year,month,inst){

    $.ajax({
        type: "GET",
        url: "users.xml",
        dataType: "xml",
        cache: false,
        success:function(data){

            console.log('reading xml file success!');
           initDaysArray( $(data) , year ,  month );

           //inst.id get the div which attached with datepicker and redraw
           $('#'+inst.id).datepicker('refresh');  
           console.log(inst.id);

        }

     });

1 个答案:

答案 0 :(得分:0)

问题是ajax是异步 - 这意味着在加载XML文件时,其余的脚本将会运行。您需要使用ajax在页面加载后立即获取XML文件,或者启用datepicker。

这意味着你应该把你的ajax代码放在Nick Craver编写的所有内容之外,因为除非加载了XML文件,否则它们将无法工作。

$.ajax({
    type: "GET",
    url: "users.xml",
    dataType: "xml",
    success: function(xml) {
        // All of Nick Craver's code here, 
        // including the initialisation code for the datepicker
    }
});

您还应该在加载XML文件之前显示加载指示符,以向您的用户指示控件尚未就绪。