gpt4 book ai didi

javascript - 在ajax之后获取php中的输入复选框值

转载 作者:行者123 更新时间:2023-11-29 21:39:51 26 4
gpt4 key购买 nike

我进行了很多搜索,但无法对我的问题应用任何答案。

我有一个由 php 生成的表单。表单结果是这样的:

<form class="add-item">
<input type="checkbox" value="1" name="cust[]">
<input type="checkbox" value="2" name="cust[]">
<input type="checkbox" value="3" name="cust[]">
<input type="checkbox" value="4" name="cust[]">
<button class="submit">
</form>

此表单可以有 4 个或 20 个输入,具体取决于产品。

所以现在我想通过ajax将选中的框发送到php。出于这个原因,我试过这个:

$.ajaxSetup({
url: "testing_cart.php",
type: 'POST',
data: 'cust='+$('.add-item input[name="cust[]"]').serialize()+'',
success: function(data){
alert(data); // to see what is going on in php
},
error: function(){
alert('dio error');
}
});
$.ajax();

在我的 PHP 文件中只有这个:

$cust = $_POST['cust'];
print_r($cust);// to see what ajax send

在某种程度上,这段代码是有效的,但并不像我预期的那样。

如果我检查唯一的一个复选框,我会得到这个结果:

cust[]='1' // the value of the checked checkbox

如果我选中超过 1 个,我会得到一个数组,但这个数组会忽略列表中的第一项...例如,下面的代码是如果我选中所有复选框...如您所见,第一个输入是忽略:

Array
(
[0] => 2 // the value of the checked checkbox
[1] => 3 // the value of the checked checkbox
[2] => 4 // the value of the checked checkbox
)

我想总是得到一个数组(如果可能的话)所以如果我的客户只选择 1 我得到:

Array
(
[0] => 2 // the value of the checked checkbox
)

如果客户选择得更好,所有的值都在一个数组中。

有什么想法吗?

附注对不起,如果我的代码词汇不是最好的

最佳答案

我觉得更简单。

 $(document).ready(function () {
$('.add-item').submit(function (event) {
var data = $('.add-item').serialize(); // send all the form data
console.log(data); // for debug only
$.ajax({
type: 'post',
url: 'form_ajax.php',
data: data,
}).done(function (data) {
console.log(data); // response from server via ajax
});
event.preventDefault(); // prevent submit
});
});

通过这种方式,您可以发送所有表格。即使您发送 1 个或 20 个值,也不会发生任何变化。

关于javascript - 在ajax之后获取php中的输入复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33364986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com