doujiongqin0687 2017-10-07 11: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 11: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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部