按数字处理输入字段



我有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...">

然后,我使用jQueryAjax对它们进行序列化,并将其发送到PHP进行验证:

$(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_2custom_9的错误。为什么以及如何解决此问题?

<input name="custom_0" type="text" placeholder="Fill this out...">
<input name="custom_1" type="text" placeholder="Fill this out...">

实际上,问题是您将在多大程度上执行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是更好的

foreach($_POST['custom'] as $stuff){}

您可以使用print_r($_POST);测试传入数据,以查看底层数据结构

请注意,使用这种方法,您无法获得$stuff所属的索引,因此使用array_keys($stuff)可以访问$_POST[custom'][$stuff]形式的元素,并使用$errors[$stuff]访问错误数组

另一种在数组上循环的方法是

foreach($_POST['custom'] as $key=>$value) 

并分别访问$key和$value,从而处理上述问题

参考https://stackoverflow.com/questions/183914/how-do-i-get-the-key-values-from-post

这是因为您正在检查PHP中所有可能的输入(在本例中为10):

for ($i = 0; $i < 10; $i++)
if(isset($_POST["custom_$i"])) {
...

你应该做的是输入你想要检查的数字,而不是总数,然后只在PHP代码中验证这些数字。

<?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
?>

您的输入仍然会被设置,尽管它们没有值。

取而代之的是:

if(isset($_POST["custom_$i"]))

做这个

if(isset($_POST["custom_$i"]) && $_POST["custom_$i"] != "")

干杯

您最好像下面的一样编写php代码

<?php
foreach($_POST as $cus){
if(!empty($cus))[
// the input is not empty

} else {
//the input is empty
}

}

并且您的输入被设置为是满的还是空的。

建议您在自己的代码中使用if(!empty($_POST["custom_$i"]))

最新更新