复选框在$ _POST中未定义,除非已选中

时间:2018-02-04 04:52:04

标签: php arrays checkbox

我有很多像这样的复选框:

<input type="checkbox" name="isGood[]">

例如,我有6个复选框,然后我检查了其中3个。当我提交时,print_r($_POST)仅返回:

Array
(
    isGood => array(
        [0] => on
        [1] => on
        [2] => on
    )
)

其他3个值未定义。我做错了什么?

2 个答案:

答案 0 :(得分:1)

好的,所以我运行了一些测试,因为我无法准确地说明你的整个代码是什么样子,也不是你使用AJAX(我更喜欢),我创建了这个简单的代码,可以引导你做一个方法,虽然在我看来不是最好的。此代码的想法是将isGood - 命名的隐藏输入值发送到同一页面,并从该字符串化的JSON对象输出生成的数组。这个对象是必需的,因为如上所述,你想要的东西不能按你想要的方式完成,因为它不是它的工作方式。 json_decode()函数用PHP创建数组。

PHP

<?php
if(isset($_POST['isGood'])){
    echo '<pre>';
    print_r(json_decode($_POST['isGood'], true));
    echo '</pre>';
}
?>

的JavaScript

<script type="application/javascript">
    // this function must be at the end of the file before closing the <body> tag
    function updateIsGoodValues(){
        let checkboxes = document.getElementsByName('isGoodValues'),
            isGood = Array();
        checkboxes.forEach(function(e, i, a){
            if(e.checked){
                isGood.push('on');
            } else {
                isGood.push('off');
            }
        });
        document.getElementById('isGoodResults').value = JSON.stringify(isGood);
    }
    updateIsGoodValues(); // makes 'off' the default value
</script>

HTML

<form method="post" action="">
    <input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
    <input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
    <input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
    <input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
    <input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
    <input type="checkbox" name="isGoodValues" onclick="updateIsGoodValues()">
    <input type="hidden" id="isGoodResults" name="isGood">
    <button>Send</button>
</form>

结果将是这样的(如果选中了第一个,第三个和第五个复选框):

Array
(
    [0] => on
    [1] => off
    [2] => on
    [3] => off
    [4] => on
    [5] => off
)

答案 1 :(得分:1)

在html中使用数组索引作为复选框,例如:

<input type="checkbox" name="isGood[1]">
<input type="checkbox" name="isGood[2]">
<input type="checkbox" name="isGood[3]">

使用以下方法检查php中的复选框:

$isGood = $_POST['isGood'];
if ($isGood) {
    if (isset($isGood[1])) {...}
    if (isset($isGood[2])) {...}
    if (isset($isGood[3])) {...}
}

更新:修复代码语法