ColdFusion 将表单数据添加到操作页面上的数组中



>问题:我有一个包含 60+ 输入的 HTML 表单,在提交时,我想使用 ColdFusion 将所有值保存到操作页面上的数组中。有没有更有效的方法来保存所有 60+ 输入的值,而不必一次提及每个输入?

正在寻找某种循环或类似的过程,可以节省我的时间,而不必在我的操作页面中写出所有输入名称。

如果需要,我可以提供我的代码示例,但它们只是标准的 HTML 表单输入(文本和选择),表单底部有一个提交按钮。

注意:看到您对 OP 的评论后,您希望批量插入到一个数据库字段中。你应该小心这一点。虽然现在很容易,但它会使在查询中处理数据变得非常非常困难,并且在冷融合中稍微困难一点。

<小时 />

这应该有效

<cfset fArr = ArrayNew(1)>
<cfset fcount = 1>
<cfloop list="#form.fieldnames#" index="f">
  <cfif not listfind("bad,field,names",f)>
    <cfset fArr[fcount] = form[f]>
    <cfset fcount = fcount + 1>
  </cfif>
</cfloop>

CFIF 是这样您就可以省略您可能想要的字段名称。如果您想收集每一个,只需将其删除即可。也许你有一个名为"gobtn"的提交按钮,你不想收集到数组中,你会让列表gobtn像<cfif not listfind("gobtn",f)>

您可以在任何作用域或结构中使用类似的东西,除了它们通常没有 fieldnames 属性或类似的东西,但 Cold Fusion 具有函数 StructKeyList() 它也适用于表单范围,但不幸的是StructKeyList(form)还包括字段fieldnames这可能会很烦人,使用内置变量更容易。

使用 URL 范围进行演示(功能上与结构相同)

<cfset fArr = ArrayNew(1)>
<cfset fcount = 1>
<cfloop list="#StructKeyList(url)#" index="f">
  <cfif not listfind("bad,field,names",f)>
    <cfset fArr[fcount] = url[f]>
    <cfset fcount = fcount + 1>
  </cfif>
</cfloop>

(Chris Tierney对ArrayAppend的使用是正确的,顺便说一句,你可以做这样更合理的事情)。我不知道为什么我没有包括它。

同样ArrayNew(1)[]是一样的,但是早期版本的 CF 不支持它,所以我习惯性地用 ArrayNew(1) 来回答。

<cfset fArr = ArrayNew(1)>
<cfloop list="#StructKeyList(url)#" index="f">
  <cfif not listfind("bad,field,names",f)>
    <cfset ArrayAppend(fArr,url[f])>
  </cfif>
</cfloop>

鉴于您的一些评论..

另一个选项是序列化JSON

你可以这样做

<cfset formCopy = Duplicate(form)>
<!--- We have to duplicate the struct so that we can safely modify a copy without affecting the original --->
<cfset DeleteItems = "fieldnames,gobtn">
<cfloop list="#deleteItems#" index="df">
  <cfset StructDelete(formCopy,df)>
</cfloop>
<cfset ForDBInsert = SerializeJSON(formCopy)>
<!--- ForDBInsert now contains a JSON serialized copy of your data. You can insert it into
  the database as such, and call it back later. --->

回拨

<cfquery name="getFD">
  select FormDump from Table
</cfquery>
<cfoutput query="getFD">
  <cfset ReBuild = DeserializeJSON(FormDump)>
  <!--- You now have a struct, Rebuild, that contains all the fields in easy to access format --->
  <cfdump var="#ReBuild#">
</cfoutput>
var fieldNameArray = listToArray(form.fieldNames);
var formArray = [];
for( fieldName in fieldNameArray ) {
    if( fieldNamme != "fieldNames" ) {
        arrayAppend( formArray, { name = fieldName, value = form[fieldName] } );
    }
}

最新更新