2012-09-10 27 views
1

我正在关注如下所示的jQuery日历示例,并试图从我的SQL数据库中加载日期而不是硬编码值示例,不知道最佳方法是什么,但我正在使用Ajax发布到我的web方法并获取数据。来自数据库的数据将被加载到一个数据表中,但问题是我不知道我的SQL数据应该以什么格式存储,以便当我检索它并将它返回给我的Ajax调用时,它可以替换“new Date( y,m,2)“。使用AJAX将日期从SQL服务器传递给jQuery日历

请协助。谢谢。

<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; 
     } 
+0

您正在使用哪种数据库/服务器端语言?数据库中有可用于保存日期的时间戳和日期时间数据类型。您的服务器端语言应该解析日期以符合您对前端的要求。 –

+0

你知道,'sDate'在ajax回调完成之前是不可用的,所以在你的例子中alert一直是空的。 – David

回答

0

Date()构造函数可以采用许多不同的参数。毫秒是相当稳定的,但是如果你的数据库存储了Unix时间戳,记得在你调用Date构造函数之前将它转换为毫秒(用1000乘以)。

旁注:您的代码无法按预期工作,因为sDate在ajax回调完成之前不可用。您需要执行以下操作:

$.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/' 
      } 
     ] 
    }); 
} 
相关问题