【发布时间】:2015-09-19 11:52:05
【问题描述】:
我有一个简单的表单,用于存储姓名、电子邮件和消息。提交后,我将 3 个字段存储在 2D 数组中,并且每次提交表单时,我都想将该数据添加到已提交的内容中。
但是,每次我提交表单时,它都不会在数组中创建一个新元素,而是会覆盖之前提交的内容。
在我的 Application.cfc 中,我声明我的数组如下:
<cffunction name="onApplicationStart">
<!--- Define array that will store form submissions --->
<cfset Application.formSubmissions = ArrayNew(2) />
</cffunction>
而我的 test.cfm 页面有主要代码:
<cfscript>
// if form submitted
if (StructKeyExists(Form,"name") AND Form.name NEQ "") {
// define constants for column names
Variables.name = 1;
Variables.email = 2;
Variables.message = 3;
// define array position
Variables.arrayLen = ArrayLen(Application.formSubmissions);
Variables.arrayPos = Variables.arrayLen + 1;
// add form data to array
Application.formSubmissions[Variables.arrayPos][Variables.name] = Form.name;
Application.formSubmissions[Variables.arrayPos][Variables.email] = Form.email;
Application.formSubmissions[Variables.arrayPos][Variables.message] = Form.message;
// reset form fields to stop insert
Form.name = "";
Form.email = "";
Form.message = "";
}
</cfscript>
<cfdump var="#Application.formSubmissions#">
<cfoutput>
<form action="##" method="post" name="contactForm" id="contactForm">
<table>
<tr>
<td><label name="nameLabel" for="name">Name</label></td>
<td><input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td><label name="emailLabel" for="email">Email</label></td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td><label name="emailLabel" for="email">Message</label></td>
<td><textarea name="message" id="message" cols="50" rows="5"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submitBtn" id="submitBtn" value="SUBMIT" /></td>
</tr>
</table>
</form>
</cfoutput>
谁能指出我哪里出错了?
【问题讨论】:
-
这看起来像是一种危险的数据存储方式。由于各种原因,应用程序可能会在您不知情的情况下重新启动。
-
这里只是一个耦合观察。应用范围在这里不是正确的方法。如果网站上不止一个人同时填写表格怎么办?您可能应该使用会话范围,并在该范围内有一个用于表单名称的子键,其中包含一个表单完成数组。其次,对于您将在 CFML 中执行的任何操作,数组数组很少是正确的数据结构。你在这里尝试做的看起来更像是一个结构数组。每个数组元素都是完成的实例(即使只是表单范围的副本也可以)。
标签: arrays forms struct coldfusion