[英]Passing javascript/Jquery array to php through a form
因此,我有一个jquery函数,用于检查选中了哪些复选框,并将ID放入数组中。 现在,该数组将传递给隐藏输入字段的值,然后提交给php脚本。 发生的情况是,看起来每个值都放在第一个索引中,而不是单个索引中。
这是获取数组中选中复选框的ID的功能。 我读到有关push的信息,到目前为止,我了解push实际上将值推入了新索引吗?
$(".article-checkbox:checked").each(function() {
multipleCheckboxes.push($(this).val());
});
我的表格:
<form id="publish-form" method="post" action="publisharticle.php" onsubmit="getMultipleCheckboxValues()">
<input type="hidden" value="" name="checkbox-value2[]" id="checkbox-value2">
li><input type="submit" value="Publish"></li>
</form>
函数onsubmit:
function getMultipleCheckboxValues(){
getValueUsingClass();
$("#checkbox-value2").val(multipleCheckboxes);
}
function getValueUsingClass(){
/* declare an checkbox array */
var chkArray = [];
var i = 0;
/* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
$(".article-checkbox:checked").each(function() {
chkArray.push($(this).val());
multipleCheckboxes.push($(this).val());
i++;
});
/* we join the array separated by the comma */
var selectedOne = chkArray[0];
var selected;
selected = chkArray.join(',') + ",";
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if(selected.length > 1){
oneCheckbox = selectedOne;
//alert("Please at least one of the checkbox" + selectedCheckboxes);
}else{
alert("Please at least one of the checkbox");
}
}
和PHP:
$checks = $_POST['checkbox-value2'];
echo $checks[0];
现在在PHP中,我想遍历数组而不是字符串。 可以说,即使我选择了索引0,我也选中了复选框1和2上面echo 1,2的php代码。我也尝试了:
var i = 0;
$(".article-checkbox:checked").each(function() {
chkArray.push($(this).val());
multipleCheckboxes[i].push($(this).val());
i++;
});
将表单数据作为键=>值提交到PHP脚本的一种更好的方法。
HTML
<form id="publish-form" method="post">
<input type="checkbox" id="checkbox1"> Checkbox1
<input type="checkbox" id="checkbox2"> Checkbox2
<input type="checkbox" id="checkbox3"> Checkbox3
<button>Submit</button>
</form>
JavaScript的
var items = {};
$('button').click(function () {
$('#public-form input').each(function () {
if ($(this).prop('checked')) {
items[$(this).id] = $(this).val();
}
});
$.post('/publisharticle.php', items).done(function (data) {
// response from php script
console.log(data);
});
});
PHP
foreach($_POST as $key => $value){
echo $key . ": " . $value . "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.