jquery复选框数组包含最后一个选中的复选框


jquery array of checkboxes contains the last one checked

我有一组复选框,我正试图通过AJAX/PHP通过POST传递这些复选框。当我填充数组时,它只会拾取最后一个。

HTML

<input type="checkbox" name="committee[]" value="membership">Membership <br/>
<input type="checkbox" name="committee[]" value="operations">Operations <br/>
<input type="checkbox" name="committee[]" value="membership">Board <br/>

Javascript

$("#save").click(function (e) { 
 ...
 var committee = { 'committee[]' : []};
  $('input:checked').each(function(){
   committee['committee[]'].push($(this).val());
 });
 $.ajax({
  url: 'save.php',
  type: 'POST',
  data: {
  ...
  committee: committee
  }
 });
});

save.php上,我现在所做的就是print_r($_POST);,并且只显示最后一个复选框。我知道我在input:checked函数中做错了什么,但我不确定是什么。

带有"[]"的数组索引可能会导致问题。改为:

  var committee = new Array();
      $('input:checked').each(function(){
       committee.push($(this).val());
     });
$("input:checked").map(function (i,e) { return $(this).val();})

将返回带有选中复选框值的数组。因此:

var committee = $("input:checked").map(function (i,e) { return $(this).val();});
$.ajax({
  url: 'save.php',
  type: 'POST',
  data: {
  ...
  committee: committee
  }
 });

我建议做$('#save').click(function(){$('#hiddendiv').post('save.php');});

或onclick=$('#hiddendiv').post('save.php');

并让save.php像这样处理文件$test=$_POST['committee'];