将jQuery UI datepicker与异步AJAX请求一起使用

时间:2015-03-13 13:11:09

标签: javascript jquery ajax jquery-ui jquery-ui-datepicker

我正在尝试在jquery-ui datepicker中启用特定日期。到目前为止,我已经设置了我的sql脚本和json文件,除响应时间外,一切正常,因为我已将async设置为false。我的jquery代码是。

var today = new Date();

$("#pickDate").datepicker({
    minDate: today,
    maxDate: today.getMonth() + 1,
    dateFormat: 'dd-mm-yy',
    beforeShowDay: lessonDates,
    onSelect: function(dateText) {
        var selectedDate = $(this).datepicker('getDate').getDay() - 1;
        $("#modal").show();
        $.get("http://localhost/getTime.php", {
            lessonDay: selectedDate,
            lessonId: $("#lesson").val()
        }, function(data) {
            $("#attend-time").html("");
            for (var i = 0; i < data.length; i++) {
                $("#attend-time").append("<option>" + data[i].lessonTime + "</option>");
                $("#modal").hide();
            }
        }, 'json');
    }
});

function lessonDates(date) {
    var day = date.getDay();
    var dayValues = [];
    $.ajax({
        type: "GET",
        url: "http://localhost/getLessonDay.php",
        data: {
            lessonId: $("#lesson").val()
        },
        dataType: "json",
        async: false,
        success: function(data) {
            for (var i = 0; i < data.length; i++) {
                dayValues.push(parseInt(data[i].lessonDay));
            }
        }
    });
    if ($.inArray(day, dayValues) !== -1) {
        return [true];
    } else {
        return [false];
    }
}

任何人都可以帮助我吗?我重复上面的代码工作正常但由于async = false而没有很好的响应时间。

谢谢!

1 个答案:

答案 0 :(得分:2)

你做错了。在您的示例中,将在该月的每一天触发同步AJAX请求。你需要重新考虑你的代码(粗略轮廓):

// global variable, accessible inside both callbacks
var dayValues = [];

$("#pickDate").datepicker({
  beforeShowDay: function(date) {
    // check array and return false/true
    return [$.inArray(day, dayValues) >= 0 ? true : false, ""];
  }
});

// perhaps call the following block whenever #lesson changes
$.ajax({
  type: "GET",
  url: "http://localhost/getLessonDay.php",
  async: true,
  success: function(data) {
    // first populate the array
    for (var i = 0; i < data.length; i++) {
      dayValues.push(parseInt(data[i].lessonDay));
    }
    // tell the datepicker to draw itself again
    // the beforeShowDay function is called during the processs
    // where it will fetch dates from the updated array
    $("#pickDate").datepicker("refresh");
  }
});

请参阅similar example here