简体   繁体   English

通过 jQuery 中的 ajax 发送多维复选框数组

[英]Sending multidimensional checkbox array via ajax in jQuery

I'm trying to post the multidimensional array values using checkbox to server side.我正在尝试使用复选框将多维数组值发布到服务器端。 But unfortunately cannot figure out the way to do it with checkbox.但不幸的是,无法弄清楚使用复选框的方法。

What I trying to do is posting the ID, (NAME, VALUE) using ajax but yet only send one single array.我想做的是使用 ajax 发布 ID (NAME, VALUE),但只发送一个数组。

 <input type="hidden" id="addon_id" value="8"> //value is dynamic
 <input type="checkbox"  name='addon[]' value="1.99"  title="Item 1"> //value and title are dynamic
 <input type="checkbox"  name='addon[]' value="5.99"  title="Item 2"> 
 <input type="checkbox"  name='addon[]' value="3.99"  title="Item 3"> 

jQuery jQuery

var addon = [];

   $.each($("input[name='addon[]']"), function() {
        if ($(this).is(":checked")) {
            addon.push($(this).val());
        }
    });

    $.ajax({
      url: '<?php echo site_url('cart/add_to_cart'); ?>',
      type: 'POST',
      data: {
        addon_id: addon_id,
        addon: addon
      },
      dataType: "JSON",
      success: function(response) {

        //response

      }
    });

currently sending format当前发送格式

[addon] => Array
        (
            [0] => 1.99
            [1] => 5.00
            [2] => 3.89
        )

Array format trying to send尝试发送的数组格式

 Array
   (
       
    [8] =>  Array(
                     [0] =>  Array( 
                                    [name] => ITEM 1
                                    [price] => 1.99
                                  )

                     [1] =>  Array( 
                                    [name] => ITEM 2
                                    [price] => 5.99
                                  ) 
  
                     [2] =>  Array( 
                                    [name] => ITEM 3
                                    [price] => 3.99
                                  )     

                        
                    )
        

  )

JSON JSON

"8":{
      "0":{ 
            "name":"ITEM 1",
           "price":"1.99"
          },
      "1":{ 
            "name":"ITEM 2",
            "price":"5.99"
          },
      "2":{ 
        "name":"ITEM 3",
        "price":"3.99"
          } 
        
    }

for the loop you have to include both values in an array:对于循环,您必须将两个值都包含在数组中:

  $.each($("input[name='addon[]']"), function() {
        if ($(this).is(":checked")) {
            addon.push({"name":$(this).attr("title"), "price":$(this).val()});
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM