使用AJAX将日期从SQL服务器传递到jQuery日历

Passing dates from SQL server to jQuery Calendar using AJAX

本文关键字:jQuery 日历 服务器 SQL AJAX 日期 使用      更新时间:2023-09-26

我正在遵循如下所示的jQuery日历示例,并试图从我的SQL数据库中加载日期,而不是示例硬编码值,不确定什么是最佳方法,但我正在使用Ajax post-to-web方法来获取数据。数据库中的数据将被加载到数据表中,但问题是我不确定SQL中的数据应该以什么格式存储,这样当我检索数据并将其返回到Ajax调用时,它可以替换"new Date(y,m,2)"。

请帮忙。谢谢

<script type='text/javascript'>
    $(document).ready(function () {
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();
        var sDate;
        $.ajax({
            type: "POST",
            url: "/WebServices/Services.asmx/GetString",
            contentType: "application/json; charset=utf-8",
            async: false,
            dataType: "json",
            success: function (result) { sDate = result.d; }
        });
        alert(sDate);
        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            editable: true,
            events: [
                {
                    title: 'Click for Google',
                    start: new Date(y, m, 2), // Hardcoded date
                    url: 'http://google.com/'
                }
            ]
        });
    });
</script>
      [WebMethod]
        public string GetString()
        { // Dump data from SQL database into DataTable
            DataTable table = new DataTable();
            table.Columns.Add("Date", typeof(DateTime));
            table.Rows.Add(DateTime.Now);
            return table;
        }
Date()构造函数可以接受许多不同的参数。毫秒是相当稳定的,但如果您的数据库存储Unix时间戳,请记住在调用Date构造函数之前将其转换为毫秒(乘以1000)。

附带说明:您的代码将无法按预期工作,因为在ajax回调完成之前,sDate不可用。你需要做一些类似的事情:

$.ajax({
    type: "POST",
    url: "/WebServices/Services.asmx/GetString",
    contentType: "application/json; charset=utf-8",
    async: false,
    dataType: "json",
    success: onSuccess
});
function onSuccess(result) {
    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        editable: true,
        events: [
            {
                title: 'Click for Google',
                start: new Date( result.d*1000 ), // assuming UNIX time
                url: 'http://google.com/'
            }
        ]
    });
}