从下拉列表中捕获值

时间:2016-12-18 18:37:54

标签: php forms drop-down-menu html-select

我尝试使用PHP从下拉列表中获取值并将其放入PHP变量

<!DOCTYPE html>
<html>
  <body>
    <form method="POST">
      <select name="class_form">
        <!--create a drop down list-->
        <option value = "Jive">Jive</option>
        <option value = "Zumba">Zumba</option>
        <option value = "Salsa">Salsa</option>
        <option value = "HipHop">HipHop</option>
        <option value = "Foxtrot">Foxtrot</option>
      </select>
      <button type="submit" name="submit_button">Select Class</button>
<?php
      //take one of the values from the drop down
      //list and put it into the $class_name variable

      $class_name = $_POST['class_form']; 

      if($_POST["submit_button"])
      {
        echo "class name caught";
        //when the submit_button is pressed the
        //value of the $class_name is echoed
        echo $class_name;
      }
?>
    </form>
  </body>
</html>

当我按下按钮时,所有发生的事情都是重置页面并且变量为空

2 个答案:

答案 0 :(得分:1)

表单的默认方法是GET,但是您尝试捕获POST变量。因此,将表单的方法更改为POST:

<form method="POST">

答案 1 :(得分:0)

您需要更新表单才能使用action属性。而且您还需要使用输入而不是按钮。

<!DOCTYPE html>
<html>
  <body>
    <!-- you need to specify the page that will treat your code, for you it's $_SERVER['PHP_SELF'] -->
    <form method="POST" action='<?php echo $_SERVER['PHP_SELF']; ?>'>
      <select name="class_form">
        <!--create a drop down list-->
        <option value = "Jive">Jive</option>
        <option value = "Zumba">Zumba</option>
        <option value = "Salsa">Salsa</option>
        <option value = "HipHop">HipHop</option>
        <option value = "Foxtrot">Foxtrot</option>
      </select>
      <!-- <button type="submit" name="submit_button">Select Class</button> -->
      <!-- you need to use an input in order to achieve your goal, not a button -->
      <input type='submit' value='Select Class' name='submit_button'>
<?php
      //take one of the values from the drop down
      //list and put it into the $class_name variable

      $class_name = $_POST['class_form']; 

      if($_POST["submit_button"])
      {
        echo "class name caught";
        //when the submit_button is pressed the
        //value of the $class_name is echoed
        echo $class_name;
      }
?>
    </form>
  </body>
</html>

$_SERVER['PHP_SELF']确保您持有表单的页面始终会处理表单,无论您选择何种名称。然后,您可以将其更改为whatever.phpstackoverflow.php,它仍将按原样运行。

PHP : $_SERVER superglobal variable