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

Get input checkbox values in php after ajax

本文关键字:输入 复选框 php ajax 之后 获取      更新时间:2023-09-26

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

我有一个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
)

如果客户选择得更好,那么数组中的所有值。

知道吗?

p.s.很抱歉,如果我的代码词汇表不是最好的

我认为更简单。

 $(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个值,也不会发生任何变化。

我怀疑问题出在data语句上。.serialize()返回一个字符串,其中包含输入字段名称及其值。您的data语句形成此字符串cust=cust[]=1&cust[]=2&cust[]=3&cust[]=4(当选中所有复选框时)。这(我在这里只是猜测)首先将数组cust[]分配给变量cust=1在查询字符串中无效而被丢弃),然后开始为该数组赋值。这就是为什么你只得到最后三个值。

为了解决您的问题,您可以将data声明更改为-

data: $('.add-item input[name="cust[]"]').serialize(),

并将您的php $cust声明更改为-

$cust = $_POST['cust[]'];

如果这在php中有效。(我几乎没有php的经验)。

下面展示了您的serialize语句正在创建的内容-

$("#serialise").click(function() {
  $("#result").text(unescape('cust=' + $('.add-item input[name="cust[]"]').serialize() + ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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 id="serialise" class="submit">Serialise</button>
</form>
<div id=result "></div>