【发布时间】:2010-11-14 02:10:13
【问题描述】:
原问题链接: Help! How to make days enabled in UI datepicker after month change?
首先,Nick Craver 的解决方案很棒。但我遇到了另一个问题:
Nick Craver 的日期源来自 js 变量 xml,但我的日期源来自 xml 文件。所以我得到了相同的日期结果,但日期选择器没有以我的方式显示。
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);
}
});
【问题讨论】:
-
是否正确获取 XML?如果在成功回调中添加
alert(data);行,它是否显示完全相同的字符串? -
是的。我用 console.log() 在 firebug 中调试。它显示从 xml 文件返回的日期。
标签: jquery ajax jquery-ui datepicker