2015-10-15 45 views
0

我有一個sql數據庫,我想用coldfusion查詢並設置成一個js數組。這樣我就可以運行我的JS函數來顯示某個日期。我的JS數組設置如下所示:從SQL的ColdFusion查詢轉換爲JS ARRAY

var natDays = [ 
    [2014, 1, 1, 'New Year'], 
    [2014, 1, 20, 'Martin Luther King'], 
    [2014, 2, 17, 'Washingtons Birthday'],  
    [2014, 5, 26, 'Memorial Day'], 
    [2014, 7, 4, 'Independence Day'], 
    [2014, 9, 1, 'Labour Day'], 
    [2014, 10, 13, 'Columbus Day'], 
    [2014, 11, 11, 'Veterans Day'], 
    [2014, 11, 27, 'Thanksgiving Day'], 
    [2014, 11, 28, 'Thanksgiving Day'], 
    [2014, 12, 25, 'Christmas'], 
    [2014, 12, 26, 'Christmas'], 
    [2015, 1, 1, 'New Year'], 
    [2015, 1, 19, 'Martin Luther King'], 
    [2015, 2, 16, 'Washingtons Birthday'],  
    [2015, 5, 25, 'Memorial Day'], 
    [2015, 7, 3, 'Independence Day'], 
    [2015, 9, 7, 'Labour Day'], 
    [2015, 10, 12, 'Columbus Day'], 
    [2015, 11, 11, 'Veterans Day'], 
    [2015, 11, 26, 'Thanksgiving Day'], 
    [2015, 11, 27, 'Thanksgiving Day'], 
    [2015, 12, 24, 'Christmas'], 
    [2015, 12, 25, 'Christmas'] 
    ]; 

dbo.Holidays
enter image description here

,所以我查詢數據庫這樣

<cfquery name="getHolidays"> 
     SELECT Holiday, date 
     FROM dbo.Holidays 
</cfquery> 

但我不知道如何轉換數據轉換爲我需要的JS格式以便使用我的功能:

var natDays = [ 
    [YEAR, MONTH, DAY, 'HOLIDAY'] 
]; 

我曾嘗試:

<cfquery name="getHolidays"> 
    select holiday, date 
    from dbo.Holidays 
</cfquery> 

<cfset aryData = [] /> 

<cfloop from="1" to="#getHolidays.recordcount#" index="j"> 
    <cfset ArrayAppend(aryData, DateFormat(getHolidays.date[j], "yyyy-mm-dd")) /> 
</cfloop> 

<cfoutput> 
    <cfdump var="#getHolidays#"> 
</cfoutput> 

<script type="text/javascript" charset="utf-8"> 
var getHolidays = <cfoutput>#serializeJson(aryData)#</cfoutput>; 
console.log(getHolidays); 
</script> 
+0

創建一個數組,循環查詢,將數組插入到數組中,每行一個,以您想要的格式插入,然後在返回之前將其序列化爲json。簡單。 –

+0

我的意思是,它與基於查詢構建表沒什麼不同,它實際上更簡單,因爲您不必處理html。 –

+0

學習總是很有趣!如果你所做的一切都是你已經知道的,那麼它會變得很無聊。 –

回答

2

所有你現在需要做的是分裂成日期年/月/日的陣列,並將它們放置到一個數組,你把它添加到結果陣列之前。

<cfquery name="getHolidays"> 
    select holiday, date 
    from dbo.Holidays 
</cfquery> 

<cfset aryData = [] /> 

<cfloop from="1" to="#getHolidays.recordcount#" index="j"> 
    <cfset dateArr = ListToArray(DateFormat(getHolidays.date[j], "yyyy-mm-dd"), '-')> 
    <cfset ArrayAppend(aryData, [dateArr[1], dateArr[2], dateArr[3], getHolidays.holiday[j]]) /> 
</cfloop> 

<cfoutput> 
    <cfdump var="#getHolidays#"> 
    <cfdump var="#aryData#"> 
</cfoutput> 

<script type="text/javascript" charset="utf-8"> 
var getHolidays = <cfoutput>#serializeJson(aryData)#</cfoutput>; 
console.log(getHolidays); 
</script> 
+0

我會剛剛使用serializeJson(getHolidays)並在JavaScript中處理它。如果你需要在多個地方進行同樣的轉換,我只會把它變成一個函數。 –