【问题标题】:How to send the values of an array of checkboxes through Ajax using jQuery?如何使用 jQuery 通过 Ajax 发送复选框数组的值?
【发布时间】:2012-09-08 03:29:02
【问题描述】:

我有一个包含很多表单域(12 x n 行)的表单。每行中的第一个字段(代表产品)是一个类似于以下内容的复选框:

<input type="checkbox" class="ids" name="ids[]" value="1">

每个复选框的值都是唯一的。

我想要做的是将检查的值发送到 PHP 脚本以通过 Ajax 进行处理。我遇到的问题是将 ID 正确地发送到服务器。我尝试过使用几种方法,包括:

$('.ids:checked').serialize();

var ids = [];
$('.ids:checked').each(function(i, e) {
    ids.push($(this).val());
});

$.ajax({
    url: "stub",
    type: "post",
    dataType: "json",
    data: {
        'ids[]': 'ids[]='+ids.join('&ids[]=')
    },
    success: function(data) {
        // stub
    }
});

但是这些都导致在服务器上得到这个:

ids[]=104&ids;[]=105

我可以序列化整个表单并将其发送过去,但这可能会导致发送大量未使用的数据。

如何仅将delete[] 的值发送到服务器?理想情况下以 PHP 将其识别为数组的方式?

(我已经通过将 ID 作为逗号分隔的字符串发送来解决这个问题,但我想知道如何实现这一点,因为我花了足够的时间试图弄清楚)。

【问题讨论】:

  • 碰巧,这些 id 是否以任何方式与您数据库中的 id 相关联?
  • data: {'ids': ids},怎么样

标签: php jquery ajax arrays


【解决方案1】:

我工作正常的解决方案

//get checkbox checked data as the array

var ids = new Array();
      $('input[name="ids[]"]:checked').each(function(){
         ids.push($(this).val());
      });



var dataString = 'ids='+ ids;


 $.ajax({
            type: "POST",
            url: "ajax_fees_pay_Directly.php",
            data: dataString,
            cache: false,
            success: function(data){

}
 });

【讨论】:

    【解决方案2】:

    为什么不将 id 作为逗号分隔的字符串发送。您可以在服务器端拆分它并应用与之关联的逻辑..

    var ids = [];
    $('.ids:checked').each(function(i, e) {
        ids.push($(this).val());
    });
    
    $.ajax({
        url: "stub",
        type: "post",
        dataType: "json",
        data: {
            'ids[]': ids.join()
        },
        success: function(data) {
            // stub
        }
    });
    

    【讨论】:

    • 如果您阅读了我的问题的底部,您会发现这就是我为解决此问题所做的工作。
    【解决方案3】:

    这对我来说很好

    <input type="checkbox" class="ids" name="ids[]" value="2">
    <input type="checkbox" class="ids" name="ids[]" value="3">
    <input type="checkbox" class="ids" name="ids[]" value="4">
    <input type="checkbox" class="ids" name="ids[]" value="5">
    <input type="checkbox" class="ids" name="ids[]" value="6">
    
    <div id="response"></div>
    <button id="submit">Submit</button>
    
    <script>
    
    $('#submit').click(function() {
    
    $.ajax({
        url: "stub.php",
        type: "post",
        data: $('.ids:checked').serialize(),
        success: function(data) {
        $('#response').html(data);
        }
    });
    
    
    });
    </script>
    

    然后在 stub.php 上

    var_dump($_POST);
    

    【讨论】:

    • 看起来我很接近,但并不完全在那里。感谢您的帮助。
    • 将所有复选框包装在表单标签中,然后序列化。
      ---- myform.serialize().
    • 它是否可以在没有表单的情况下工作,并且没有指定type: "post",
    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 2015-07-20
    • 2021-09-22
    • 1970-01-01
    • 2016-07-16
    • 2016-11-05
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多