从SQL转换成JS ARRAY的ColdFusion查询

时间:2015-10-15 18:46:18

标签: jquery coldfusion

我有一个sql数据库,我想用coldfusion查询并设置成一个js数组。这样我就可以运行我的JS函数来显示某个日期。我的JS数组设置如下:

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>

1 个答案:

答案 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>