【问题标题】:Storing jquery appended value存储jquery附加值
【发布时间】:2012-08-24 07:57:46
【问题描述】:

我有一个 html 表单,我在其中添加了一些元素,例如,当用户从列表中选择多个国家/地区时,jquery 会遍历所选列表并为每个国家/地区创建一组表单字段。

假设用户选择了美国、中国和印度,那么将为每个国家创建表单字段,并将 id asn 命名为 *countryName_indexValue, customeName_countryName_indexValue.*

我的问题: 当用户填写并点击提交按钮时,我需要通过 php 将此附加元素值提交到 mysql 数据库。我该怎么做?请帮帮我......

结果是这样的

<form>

<table>
<thead>
<tr>
<td>Country Name</td>
<td>Data01</td>
<td>Data02</td>
</tr>
</thead>

<!-- APPENDED ELEMENTS -->

<tbody>
<tr id="usa_0">
<td><input type="text" name="userCountry_usa_0" id="userCountry_usa_0"></td>
<td><input type="text" name="countryData01_usa_0" id="countryData01_usa_0"></td>
<td><input type="text" name="countryData02_usa_0" id="countryData02_usa_0"></td>
</tr>

<tr id="china_1">
<td><input type="text" name="userCountry_china_1" id="userCountry_china_1"></td>
<td><input type="text" name="countryData01_china_1" id="countryData01_china_1"></td>
<td><input type="text" name="countryData02_china_1" id="countryData02_china_1"></td>
</tr>

<tr id="india_2">
<td><input type="text" name="userCountry_india_2" id="userCountry_india_2"></td>
<td><input type="text" name="countryData01_india_2" id="countryData01_india_2"></td>
<td><input type="text" name="countryData02_india_2" id="countryData02_india_2"></td>
</tr>
</tbody>

</table>

</form>

谢谢你..

【问题讨论】:

  • 我可以看看你尝试过的代码,以便我们可以修改它吗?

标签: php jquery mysql forms


【解决方案1】:

那么问题是什么?您在提交数据时遇到问题了吗?或者您是否正在努力处理 PHP 端的 $_POST ?

如果它正在处理 $_POST,我建议将生成的表单字段更改为具有 userCountry[countryName][indexValue] 形式的 ID,而不是 userCountry_countryName_indexValue

这样,当提交表单时,$_POST 将包含数组,然后您可以循环写入数据库,例如$_POST 会是这样的:

$_POST['userCountry'] = array( 'usa' => array( '0' => 'someValue'),
                               'china' => array( '1' => 'someOtherValue'),
                               'india' => array( '2' => 'yetAnotherValue'),
                        )

然后你可以循环这个,例如:

foreach($_POST['userCountry'] as $country=>$subArray) {
    //code here to insert data
}

您当前的实现也可以使用循环,只要您遍历整个 $_POST 对象,检查每个键,并查找特定的子字符串,在下划线处爆炸,然后处理,但它会是有点丑。

【讨论】:

  • 感谢您的回复。问题是,如果我有一个具有唯一 ID/名称的自定义字段,例如 name="fieldName",那么我可以有一个 $varName = $_POST['fieldName' ];在我的 php 页面中,我将把这个变量发送到 mysql 查询,以便它可以将值存储在数据库中。但是在这里,我正在为每个选定的国家/地区生成一组新的字段。因此,如果用户选择 50 个国家/地区,每个字段都会有一个 id 和 name,如我上面列出的。在这种情况下,我如何处理各个国家/地区的字段,例如我需要将每个国家及其数据作为新记录输入到 mysql 表中。
  • @sravis - 我已经更新了我的答案,更详细地说明了如何更改生成的表单元素的 id 将允许您遍历表单数据以将其插入数据库。
  • 感谢您的帮助,现在我可以遍历每个字段并将其存储在数据库中。我发现这对我的问题非常有用stackoverflow.com/questions/12040425/…
【解决方案2】:

在表单提交事件或元素点击时,您可以使用 jQuery 的 .post() 或 .get() 函数将输入值发送到 php 文件。

这里有一些关于如何使用 .post() 的基本和更复杂的例子: http://api.jquery.com/jQuery.post/

强烈建议 php 文件包含数据验证,然后您可以从那里发出带有 php 的 sql insert。

【讨论】:

  • 问题不在于如何通过表单提交数据。 . .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 2012-04-19
  • 2020-11-24
相关资源
最近更新 更多