如何获取数组post值



在我的脚本中,我有动态添加的输入字段。我必须使用php获取所有输入值,但问题是$_POST['poids']只给了我输入数组的第一个值,所以只给了数组poids的第一个元素。这是我的代码:

$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
<a href="#" class="delete">Delete</a>
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>

获取post(postForm.php(:

$poids = $_POST['poids'];
foreach($poids as $poid) {

echo " -->" .$poid;
}

我希望你不明白我的意思。

提前感谢

问题是您将带有新输入字段的div附加到$wrapper,但这在表单之外。您需要将其放入表单中。

更改

$wrapper.append($form_colis); //add input box

$('.item', $wrapper).last().after($form_colis); //add input box

我不是PHP专家,但通过浏览提供的代码,您似乎只是在搜索名称值为poids的输入。

const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()

然后,当您创建bew输入时,您不会将poid附加到输入名称。

const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);

因此,你只会用你的方法找到一个,那就是这个:

<input type="text" placeholder="Poids" name="poids[]">

因此,为了解决这个问题,我相信在$form_colis方法中,添加poids

最新更新