doujiongqin0687 2017-10-07 19:27
浏览 55
已采纳

为什么在没有选择它们时,HTTP POST方法的$ _POST超全局数组中缺少表示单选按钮的键?

I've written following PHP code :

<!DOCTYPE HTML>  
<html>
  <head>
  </head>
  <body>  

    <?php
      // define variables and set to empty values
      $name = $email = $gender = $comment = $website = "";

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";
        die;  
      }
    ?>

    <h2>PHP Form Validation Example</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
      Name: <input type="text" name="name">
      <br><br>
      E-mail: <input type="text" name="email">
      <br><br>
      Website: <input type="text" name="website">
      <br><br>
      Comment: <textarea name="comment" rows="5" cols="40"></textarea>
      <br><br>
      Gender:
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <br><br>
      <input type="submit" name="submit" value="Submit">  
    </form>
  </body>
</html>

When I submitted the form without entering data in any of the form firled or selecting any of the two radio buttons that are present on the HTML form I got following result :

Array
(
    [name] => 
    [email] => 
    [website] => 
    [comment] => 
    [submit] => Submit
)

In above result, I could see the names of all input form controls, even the key representing the text-area is also present within the $_POSTarray. The only expected thing that is missing from the above $_POST array output is the key representing the radio buttons 'gender'

This is my doubt. Why it's going missing from the output of $_POST array?

When I fill in the form controls, select any of the radio buttons everything works fine, no issues with it.

Are there any other similar HTML form controls which behave like radio buttons are behaving in above code which I have written?

Please someone clear my doubt and explain me the reason behind this behavior.

Thank You.

  • 写回答

1条回答 默认 最新

  • dongwo7858 2017-10-07 19:32
    关注

    Because when you don't select a radio input, no data is sent to the server. As shown in the MDN:

    Note: If no radio button is selected when the form is submitted, there is no value submitted to the server to represent the unselected state (e.g., value=unselected); the value is not submitted to the server at all.

    Source

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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时遇到的编译问题