2015-10-27 36 views
1

如何序列化日期以用於AJAX?我正在使用ajax從隱藏的輸入文本框發送日期,並希望序列化它以使用coldfusion運行查詢。使用AJAX序列化日期

HTML(自動接收日期)

JS

var Tmrwdate = $('#TomorrowsDate'); 
console.log($(Tmrwdate).serialize()); 
    $.ajax({ 
      url: "proxy/TomorrowsDate.cfm", 
      type: "post", 
      dataType: "json", 
      data: {date: Tmrwdate.serialize() }, 
      success: function (data) { 
       console.log(data); 
      }, 
      error: function (xhr, textStatus, errorThrown) { 
       console.log(errorThrown); 
      } 
     }); 

代理/ TomorrowsDate.cfm

<cfset session.dealerwork.tomorrowsdate = form.TomorrowsDate > 

<cfquery name="tomorrowTextArea"> 
    SELECT * 
    FROM dbo.Dealer_Track_Work 
    WHERE Date_Due = <cfqueryparam value="#session.dealerwork.tomorrowsdate#" /> 
    AND Date_Complete IS NULL  
</cfquery> 


<cfoutput>#SerializeJSON(session.dealerwork.tomorrowsdate)#</cfoutput> 

我的控制檯日誌從console.log($(Tmrwdate).serialize());

TomorrowsDate=10%2F28%2F2015 
+1

JSON有沒有日期特殊格式所以只要你的客戶和ColdFusion可以達成一致的東西,只是使用它。例如。 YYYY-MM-DD – Henry

回答

3

你不應該需要序列化的日期,只是在你的數據參數發送的值。

JS

var Tmrwdate = $('#TomorrowsDate').val(); 

$.ajax({ 
     url: "proxy/TomorrowsDate.cfm", 
     type: "post", 
     dataType: "json", 
     data: {date: Tmrwdate }, 
     success: function (data) { 
      console.log(data); 
     }, 
     error: function (xhr, textStatus, errorThrown) { 
      console.log(errorThrown); 
     } 
    }); 

代理/ TomorrowsDate.cfm

<cfset session.dealerwork.tomorrowsdate = form.TomorrowsDate > 
<cfset result = { TomorrowsDate = form.TomorrowsDate} /> 

<cfquery name="tomorrowTextArea"> 
    SELECT * 
    FROM dbo.Dealer_Track_Work 
    WHERE Date_Due = <cfqueryparam value="#session.dealerwork.tomorrowsdate#" /> 
    AND Date_Complete IS NULL  
</cfquery> 


<cfoutput>#SerializeJSON(result)#</cfoutput> 
+0

該錯誤可能是指服務器*返回的內容*,而不是發送到服務器的內容 – beloitdavisja

+0

您需要發回數據結構,而不僅僅是單個值。我不確定返回剛剛發送的確切數據的目的是什麼,但是我已經更新了返回一個序列化結構('result')的答案 – beloitdavisja

+0

您確定您的CF頁面沒有拋出錯誤嗎? – beloitdavisja

1

您可以格式化的日期,但是你想或者真的是你的終點期待它

function formatMyDate(date){ 

var day = date.getDate(); 
var monthIndex = date.getMonth(); 
var year = date.getFullYear(); 
return day+'/'+monthIndex+'/'+year; 
} 



$.ajax({ 
     url: "proxy/TomorrowsDate.cfm", 
     type: "post", 
     dataType: "json", 
     data: {date: formatDate(new Date()) }, 
     success: function (data) { 
      console.log(data); 
     }, 
     error: function (xhr, textStatus, errorThrown) { 
      console.log(errorThrown); 
     } 
    }); 

或者你c一個避免重新發明輪子,並使用類似momentjs http://momentjs.com/

$.ajax({ 
     url: "proxy/TomorrowsDate.cfm", 
     type: "post", 
     dataType: "json", 
     data: {date: moment().format("YYYY-MM-dd") }, 
     success: function (data) { 
      console.log(data); 
     }, 
     error: function (xhr, textStatus, errorThrown) { 
      console.log(errorThrown); 
     } 
    });