在FormData的情况下,复选框数组无法通过ajax传递给php。以下脚本在没有使用FormData的情况下正常工作。所以我假设问题在于附加在FormData中或从中传递。它返回invalid arguments supplied for foreach()
。
复选框不是表单元素的一部分,因此
<input type="checkbox" id="menu" name="menu[]" value="1">
<input type="checkbox" id="menu" name="menu[]" value="2">
<input type="checkbox" id="menu" name="menu[]" value="3">
<form id="form">
...........
</form>
Jquery和ajax
$(document).on('submit', '#form', function(e){
e.preventDefault();
var navid = [];
$("[name='menu[]']:checked").each(function (i) {
navid[i] = $(this).val();
});
if (navid.length === 0){ //tell you if the array is empty
alert("Please Select atleast one checkbox");
}
else {
var formData = new FormData(this);
formData.append('navid', navid);
$.ajax({
type: 'POST',
url: 'upload.php',
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert(data);
}
});
}
});
PHP
foreach ($_POST["navid"] AS $key => $item){
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menunin',$_POST["menunin"][$key]);
$query1->bindParam(':menueng',$_POST["menueng"][$key]);
$query1->bindParam(':navid',$item);
$query1->execute();
echo 'Menu has inserted';
}
答案 0 :(得分:1)
您的PHP代码中有问题:
您正在传递逗号分隔值,因此首先爆炸并使用
$data = explode("," ,$_POST["navid"]);
foreach ($data AS $key => $item){
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menunin',$_POST["menunin"][$key]);
$query1->bindParam(':menueng',$_POST["menueng"][$key]);
$query1->bindParam(':navid',$item);
$query1->execute();
echo 'Menu has inserted';
}