【问题标题】:Use jQuery UI datepicker with async AJAX requests使用带有异步 AJAX 请求的 jQuery UI 日期选择器
【发布时间】:2015-03-13 13:11:09
【问题描述】:

我正在尝试在 jquery-ui 日期选择器中启用特定日期。到目前为止,我已经设置了我的 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 而响应时间不好。

谢谢!

【问题讨论】:

  • 这引出了一个问题,你为什么使用async: false
  • 因为如果我使用 async: true 什么都不会从服务器返回...

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


【解决方案1】:

你做错了。在您的示例中,该月的每一天都会触发一个同步 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

【讨论】:

    猜你喜欢
    • 2012-11-17
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2014-10-20
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多