我的问题是,在将JSON响应发送到浏览器之前,日历正在呈现。换句话说,当我们进入数组搜索时,我的数组是空的。我该如何解决这个问题?
更新:我放弃了尝试在月份更改时请求更多日期,所以现在我只是在第一次通话时获得大约6个月的活动并立即显示。以下是工作代码。
$(document).ready(function () {
var actionCalDates = [];
//var orgID = 0;
var currentDate = new Date();
dateCount = 0;
getDates(1, currentDate.getMonth(), currentDate.getFullYear());
function displayCalendar() {
$("#calendar").datepicker({
dateFormat: 'dd/mm/yyyy',
beforeShowDay: function (thedate) {
var theday = (thedate.getMonth() + 1) + "/" + thedate.getDate() + "/" + thedate.getFullYear();
//console.log("Before the if my array contains: " + actionCalDates);
if ($.inArray(theday, actionCalDates) == -1) {
//console.log(theday + " Not Found");
return [false, "", ""];
} else {
//console.log(theday + " Found");
return [true, "specialDate", "Actions Today"];
}
}
});
}
function getDates(orgID, month, year) {
dateCount += 1;
if (dateCount < 4) {
$.ajax({
url: "/Calendar/getEvents",
data: {
'orgID': orgID,
'month': month,
'year': year
},
type: "GET",
dataType: "json",
success: function (result) {
//console.log(result);
for (var i in result) {
actionCalDates.push(result[i]);
//console.log("Pushed to the array: " + actionCalDates[i]);
}
//console.log("Array currently holds: " + actionCalDates);
displayCalendar();
}
});
}
}
});
C#控制器背后的代码:
public JsonResult getEvents(int orgID, int month, int year)
{
DateTime orgDate = Convert.ToDateTime(month + "/" + orgID + "/" + year);
var fromDate = orgDate;
var toDate = orgDate.AddMonths(7); //last month and the next 6 months
var events = db.Events.Where(e => e.StartDate >= fromDate && e.EndDate <= toDate).ToArray();
var eventlist = from e in events
select new
{
date = e.StartDate.ToString(),
};
List<string> EventDates = new List<string>();
foreach (var currentEvent in eventlist)
{
DateTime dt;
dt = Convert.ToDateTime(currentEvent.date.ToString());
EventDates.Add(dt.Month + "/" + dt.Day + "/" + dt.Year);
}
return Json(EventDates, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:0)
将呈现日历的代码放入一些任意函数,然后在ajax({success:})函数中调用该函数
即
function renderCalendar(){
$("#calendar").datepicker({
...
});
}
success: function (result) {
...
renderCalendar();
}
答案 1 :(得分:0)
为什么不将$("#calendar").datepicker({
调用放在ajax success:
处理程序中:
success: function (result) {
console.log(result);
for (var i in result) {
actionCalDates.push(result[i]);
console.log("Pushed to the array: " + actionCalDates[i]);
}
//actionCalDates = actionCalDates.concat(result);
console.log("Array currently holds: " + actionCalDates);
//getDates(orgID, month + 1, year);
//getDates(orgID, month - 1, year);
//Now we have filled the array, let's create our calendar..
$("#calendar").datepicker({
....
}
答案 2 :(得分:0)
我认为你想要的方法叫做onChangeMonthYear。
我在tutorial I wrote up中使用过它。它可能不是有史以来最漂亮的代码,但它似乎基本上起作用。