我在页面nice.php
上的表单内选择一个下拉列表,使用按钮提交
<form action="nice.php" method="post">
<select name="CarList">
<option value="0"> - Select Car - </option>
<option value="AM">Aston Martin</option>
<option value="KG">Koenigsegg</option>
<option value="MB">Mercedes Benz</option>
</select>
<input type="submit">
</form>
在做出选择之后,是否可以提交表单,重新加载同一页面但是从下拉列表中的值变为php变量$SelectedCar
?
答案 0 :(得分:1)
if(!empty($_POST['CarList'])){
$SelectedCar = $_POST['CarList'];
echo $SelectedCar;
}else{
echo '<p>No Selection has been made and submitted yet</p>';
}
答案 1 :(得分:0)
将代码添加到php页面的顶部并删除表单标记。这应该回到同一页面。 (请记住检查是否在$ _POST中设置了任何变量)
我还没有测试过这个建议,但它应该可行
**编辑。
所以你的HTML应该是这样的:
<?php
if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
$CarListValue = $_POST['CarList'];
if($CarListValue != 0){ // a selection has been made using car list
$SelectedCar = $CarListValue
echo $SelectedCar // should print either 'AM', 'KG', or 'MB'
}
else{
echo '<p>No Selection has been made and submitted yet</p>';
}
}
?>
<html>
<head>
<title>Nice.php</title>
</head>
<body>
<select name="CarList">
<option value="0"> - Select Car - </option>
<option value="AM">Aston Martin</option>
<option value="KG">Koenigsegg</option>
<option value="MB">Mercedes Benz</option>
</select>
<submit>Submit Form</submit>
</body>
</html>
然后你可以将你的验证带到另一个级别并改变这样的PHP代码:
<?php
$ValidCars = array('AM','KG','MB');
if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
$CarListValue = $_POST['CarList'];
if(in_array($CarListValue,strtoupper($ValidCars),false) !== true){
die('<b>The car selection you made is invalid</b>');
}
if($CarListValue != 0){ // a selection has been made using car list
$SelectedCar = $CarListValue
echo $SelectedCar // should print either 'AM', 'KG', or 'MB'
}
else{
echo '<p>No Selection has been made and submitted yet</p>';
}
}
?>
我只想再说一遍,这段代码未经测试但理论上代码应该没有任何错误