使用 $_POST 发送单选框值

2022-01-21 00:00:00 post radio-button forms php html

即使字段为空,如何将单选或复选框值发送到 $_POST 数组?

How can I send a radio or checkbox value to the $_POST array even when the field is empty?

<?php
    if(isset($_POST)) {
        echo '<pre>';
        print_r($_POST);
        echo '</pre>';
    }
?>

<form action="test.php" method="POST">
    <input type="text" name="name">
    <input type="text" name="email">
    <input type="radio" name="gender">

    <input type="submit"> 
</form>

如果我在没有填写数据的情况下点击提交,这就是我从页面中得到的结果.

Here is what I get from the page if I hit submit without even filling out data.

Array
(
    [name] => 
    [email] => 
)

如您所见,在不触及输入类型文本的情况下,它们的值被推送到 $_POST 数组.如何使用单选框做到这一点?我基本上想设置"它,虽然它和文本输入一样是空白的.

As you see, without touching the input type text, their value was pushed to the $_POST array. How can I do this with the radio box? I essentially want to "set" it, although it is blank just like the text inputs.

我知道我总是可以打电话

I know I could always call

<?php
  if(isset($_POST['gender'])) {
     //Code
  }
?>

但这不一定是我想要的.我需要它自动设置.提前致谢!

But that's not necessarily what I'm looking for. I need it to set automatically. Thanks in advance!

推荐答案

试试这个就行了:

Unchecked radio 元素不会被提交,因为它们不被视为成功.所以你必须检查它们是否使用 issetempty 函数发送.

Unchecked radio elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.

<?php
    if(isset($_POST)) {
        echo '<pre>';
        print_r($_POST);
        echo '</pre>';
    }
?>

<form action="test.php" method="POST">
    <input type="text" name="name">
    <input type="text" name="email">
    <input type="radio" name="Gender" value="1"/>Male
    <input type="submit" name="submit" value="submit"/>
</form>

相关文章