我很难从序列化表单的 ajax 发送中检索我调用的 PHP 中的复选框数组数据。我可以调用所有其他表单字段,但不能调用复选框数组。有人可以帮忙吗?我在这里拔头发。 :(
我的表格:
<form id="registration" method="POST" action="">
<input type="text" id="pFirst" name="pFirst" class="form-control" placeholder="First">
<input type="text" id="pLast" name="pLast" class="form-control" placeholder="Last">
<input type="checkbox" name="class[]" value="1">
<input type="checkbox" name="class[]" value="2">
<input type="checkbox" name="class[]" value="3">
<input type="checkbox" name="class[]" value="4">
<button type="submit">Register</button>
</form>
我的ajax:
function OnSubmit(form){
$.ajax({
url:'processRegistration.php',
type:'post',
data: $(form).serializeArray(),
success:function(response){
var msg = "";
if(response == "1"){
msg = "Registration Received";
}else{
msg = "Sorry, something went wrong. Please contact the Web Admin.";
}
//alert(msg);
alert(response);
}
});
}
我的 PHP 接收器:
echo $_POST['pFirst'].', '.$_POST['pLast'].', '.$_POST['class'];
在我的 Ajax 中,我提醒了响应,以便我可以看到返回的内容。如果我按照代码中显示的方式将回声留在接收器中,则会收到错误“未定义的数组键'类'”。如果我保留 $_POST['class'] 关闭,我会得到名字和姓氏。我还查看了这个解决方案:发送带有选中复选框值的数组并在 php 中检索为字符串但它使用 JSON.stringify() 并且我想将表单数据保留为 URL 编码格式。
我需要做的是能够访问序列化表单传递的选中复选框,同时仍然能够将每个传递的表单字段作为 $_POST 项调用。
查看您的说明,我认为应该可以直接在php中通过使用
$_POST['class']
直接获取您想要的数据,但您说这是不可能的,所以我可以为您提供如何检查这一点的想法你可以尝试一下。
首先,您需要打印 serializeArray() 方法的结果,以确保传输出正确的数据:
$(document).ready(function () {
$("#registration").on("submit", function (event) {
console.log($(this).serializeArray());
event.preventDefault();
});
})
<head>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
</head>
<form id="registration" method="POST" action="">
<input type="text" id="pFirst" name="pFirst" className="form-control" placeholder="First">
<input type="text" id="pLast" name="pLast" className="form-control" placeholder="Last">
<input type="checkbox" name="class[]" value="1">
<input type="checkbox" name="class[]" value="2">
<input type="checkbox" name="class[]" value="3">
<input type="checkbox" name="class[]" value="4">
<button type="submit">Register</button>
</form>
也可以直接使用F12工具查看ajax发送出去的数据在此输入图片描述
如果传出的数据没问题,那么就在php中接收到了,就可以通过了
var_export($_POST);die();
确认所有的post数据数组,你会看到其中一个key是class,他的值是一个数组,里面就是你所有勾选的checkbox的值,他大概是这样的:
array (
'pFirst' => '123',
'pLast' => '123',
'class' =>
array (
0 => '3',
1 => '4',
),
)