ajax 调用上的 PHP 求和复选框值


PHP sum checkbox values on ajax call

我想通过ajax请求对选中的复选框值求和。

<form1>
<input type='checkbox' name='check_box[]' value='value01'>
</form1>
<form2>
<input type='checkbox' name='check_box[]' value='value02'>
</form2>
<form3>
<input type='checkbox' name='check_box[]' value='value03'>
</form3>

我正在使用 ajax 表单序列化:

 data: $(this.form).serialize(),
            url: 'file.php',
            dataType: 'json',
             ....

而PHP文件内容是:

$sum=0;
foreach($_POST['check_box'] as $shipping) {
    $shipping = $shipping;
    $sum +=  $shipping;
  }
  echo json_encode($sum);

但是 Ajax 返回错误?可能是因为多种形式吗?

<form name="form1" id="form1">
<input type='checkbox' name='check_box[]' class="cb" value='1'>
</form>
<form name="form1" id="form1">
<input type='checkbox' name='check_box[]' class="cb" value='2'>
</form>
<form name="form1" id="form1">
<input type='checkbox' name='check_box[]' class="cb" value='3'>
</form>

您的 jquery 脚本:-

$(document).ready(function(){
    $(".cb").click(function(){
        var values = new Array();
        $.each($("input[name='check_box[]']:checked"), function() {
          values.push($(this).val());
        });
        //alert(values);
        $.ajax({url: "urphppage.php", 
        type:'POST',
        data:{ 'cbs':values},
        success: function(result){
             resp = JSON.parse(result);
             alert(resp.sum)
        }
        });
    });
});

还有你的php页面:-

$msg = array();
$sum=0;

foreach($_POST['cbs'] as $shipping) {
    $sum +=  $shipping;
}
$msg['sum'] = $sum;
echo json_encode($msg);