dongnvwang8591 2017-03-03 20:53
浏览 48
已采纳

PHP复选框验证,如果是其他问题

I have a checkbox in my HTML file:

<input type="checkbox" id="kopia" name="kopia" class="form-input" value="0">

I'm trying to pass to the PHP file (via AJAX) a couple of values, one of them is a boolean value created by a checkbox (simplified):

name: "kopia"
value: document.getElementById("kopia").checked

If I check via console, it returns true if checked and false if unchecked.

document.getElementById("kopia").checked

If I check via PHP file, it behaves the same:

echo $_POST['kopia']

But when I write something like this:

$checkbox = $_POST['kopia'];
if ($checkbox){
    echo "hey";
} else {echo "bye";}

It always returns "hey", no matter if the checkbox was checked or not. I don't get it. Even if I make something like this:

$checkbox = $_POST['kopia'];
if ($checkbox){
    echo $checkbox;
} else {echo "bye";}

It never returns "bye", no matter if the box was checked or not, but returns true if checked and false if unchecked. This thing has already stolen a couple of hours and that's a couple of hours too much. Any idea, hint?

  • 写回答

2条回答 默认 最新

  • duansao20000508 2017-03-03 21:07
    关注

    Your are passing true or false in $_POST['kopia'] via the return of document.getElementById("kopia").checked, however $_POST values are strings in PHP. So both string "true" and string "false" will evaluate to boolean true in your current if condition. You can check the string value:

    $checkbox = $_POST['kopia'];
    if ($checkbox == "true"){
        echo $checkbox;
    } else {
        echo "bye";
    }
    

    Or you can convert them to a boolean, see PHP: Validate Filters (thanks to Sysix):

    $checkbox = filter_var($_POST['kopia'], FILTER_VALIDATE_BOOLEAN);
    

    Or if you set $_POST['kopia'] to 0 or 1, those strings will be evaluated correctly in your current if condition.

    Or you could abandon the JS value switching and just check if $_POST['kopia'] exists (only when checked):

    if(isset($_POST['kopia'])) {
        echo "hey";
    } else {
        echo "bye";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题