2015-03-13 43 views
0

我想在jQuery UI日期選擇器中啓用特定的日子。到目前爲止,我已經設置了我的sql腳本和json文件,並且除了響應時間之外,一切正常,因爲我已將async設置爲false。我的jQuery代碼是。使用jQuery UI datepicker與異步AJAX請求

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而導致響應時間不佳。

謝謝!

+0

這引出了一個問題,你爲什麼使用'async:false'? – j08691 2015-03-13 13:12:29

+0

因爲如果我使用異步:真正沒有從服務器返回... – Antegeia 2015-03-13 13:16:46

回答

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

+0

謝謝Soooooo多薩爾曼!!!你是一個真正的救星! – Antegeia 2015-03-13 14:18:13