使用$ _POST从HTML获取选择选项值


Answers:


203

使用这种方式:

$selectOption = $_POST['taskOption'];

但是,最好给<option>标签赋值。

<select name="taskOption">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
</select>

为什么给<option>标签赋予值总是更好呢?“ 如果不包含value属性,则该值默认为元素 “中包含的文本。如果有效,那怎么了?
osullic

3
@osullic同意,但是我想5年前,有些浏览器没有这么做。
Praveen Kumar Purushothaman

28

您可以$_POST通过键访问数组中的值。$ _POST是一个关联数组,因此taskOption您可以使用访问$_POST['taskOption'];

不过,请确保在继续$ _POST数组之前检查它是否存在。

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

14

您也可以这样做:

<?php
if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
    switch ($select1) {
        case 'value1':
            echo 'this is value1<br/>';
            break;
        case 'value2':
            echo 'value2<br/>';
            break;
        default:
            # code...
            break;
    }
}
?>


<form action="" method="post">
    <select name="select1">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
    <input type="submit" name="submit" value="Go"/>
</form>

11
<select name="taskOption">
      <option value="first">First</option>
      <option value="second">Second</option>
      <option value="third">Third</option>
</select>

$var = $_POST['taskOption'];

3

取决于select所包含的表单的方法设置为“ get”还是“ post”。

如果<form method="get">是,则select的值将位于超级全局数组中$_GET['taskOption']

如果<form method="post">是,则select的值将位于超级全局数组中$_POST['taskOption']

要将其存储到变量中,您将:

$option = $_POST['taskOption']

有关更多信息的好地方是PHP手册:http : //php.net/manual/zh/tutorial.forms.php



1
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>

试试这个

<?php 
if(isset($_POST['button_name'])){
$var = $_POST['taskOption']
if($var == "1"){
echo"your data here";
}
}?>

1


-html文件-

<select name='city[]'> 
                <option name='Kabul' value="Kabul" > Kabul </option>
                <option name='Herat' value='Herat' selected="selected">             Herat </option>
                <option name='Mazar' value='Mazar'>Mazar </option>
</select>

-php文件-

$city = (isset($_POST['city']) ? $_POST['city']: null);
print("city is: ".$city[0]);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.