我有10个输入字段是可选的,由用户填写,并在点击“添加另一个字段”时通过jQuery动态添加。他们的名字如下:
<input name="custom_0" type="text" placeholder="Fill this out...">
<input name="custom_1" type="text" placeholder="Fill this out...">
<input name="custom_2" type="text" placeholder="Fill this out...">
...
<input name="custom_9" type="text" placeholder="Fill this out...">然后我使用PHP对它们进行序列化,并将其发送到jQuery进行验证:
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'php/form_handler.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});这是我现在拥有的PHP。它包含一个循环,循环10次,如果未设置字段,则返回一个错误:
<?php
$errors = array();
for ($i = 0; $i < 10; $i++) {
if(isset($_POST["custom_$i"])) {
// input is set, continue verification code...
} else {
$errors["custom_$i"] = "ERROR!";
}
}
// code to echo back errors
?>我现在遇到的问题是,如果用户只填写了10个输入中的2个,它仍然会返回输入3-10的错误,即使这些输入从未被设置或填写。
例如,如果用户只填写了这些输入,然后提交了表单,则会将输入custom_2的错误返回给custom_9。我怎么才能解决这个问题?
<input name="custom_0" type="text" placeholder="Fill this out...">
<input name="custom_1" type="text" placeholder="Fill this out...">发布于 2014-01-11 21:53:44
实际上,问题在于您将在多大程度上执行custom_$i检查..。由于输入的维度是动态的,您应该重新考虑代码,并将POST数据作为数组发送,并使用foreach对其进行迭代。
生成输入字段的模板应该是
<input name="custom[0]" type="text" placeholder="Fill this out...">
<input name="custom[1]" type="text" placeholder="Fill this out...">然后访问数据只需使用foreach或从数组的0到长度开始.但厄勒奇更好
foreach($_POST['custom'] as $stuff){}您可以使用print_r($_POST);测试传入数据,以查看底层数据结构。
请注意,使用这种方法无法获得$stuff所属的索引,因此使用$errors$stuff可以以$_POST'custom'的形式访问元素并访问错误数组
另一种遍历数组的方法是
foreach($_POST['custom'] as $key=>$value) 并分别访问$key和$value,从而处理上述问题。
参考于https://stackoverflow.com/questions/183914/how-do-i-get-the-key-values-from-post
发布于 2014-01-11 21:50:40
这是因为您正在检查PHP中所有可能的输入(在本例中为10):
for ($i = 0; $i < 10; $i++)
if(isset($_POST["custom_$i"])) {
...您应该做的是传递您想要检查的数字,而不是总数,然后只验证PHP代码上的数字。
发布于 2014-01-11 21:51:12
<?php
$errors = array();
for ($i = 0; $i < 10; $i++) {
if(isset($_POST["custom_".$i])) {
// input is set, continue verification code...
} else {
$errors["custom_".$i] = "ERROR!";
}
}
// code to echo back errors
?>https://stackoverflow.com/questions/21068262
复制相似问题