如何根据select标签选中的不同option值跳转至对应页面?
你的代码一共有3处核心错误,导致跳转逻辑无法运行:
- 表单中的
<select>标签未添加name属性,表单提交时只会提交带有name属性的字段,因此后端$_POST无法获取到选中的支付方式值 - PHP逻辑中判断的是
isset($_POST["paymentmethod"]),但你表单里提交按钮的name是submit,没有任何名为paymentmethod的表单字段,所以这个判断永远为假,跳转逻辑根本不会执行 - PHP的
header()跳转要求执行前不能有任何输出(包括HTML代码、空格、换行等),你现在把PHP逻辑写在HTML代码之后,输出已经发送给浏览器,此时调用header()会抛出警告,跳转失败
修复方案
- 给
<select>标签添加name="payment"属性 - 将PHP跳转逻辑挪到页面最顶部,所有HTML输出之前
- 把PHP的判断条件改为判断
isset($_POST["submit"]),和提交按钮的name对应
修改后完整代码
页面顶部PHP代码(必须放在所有HTML内容最前面,前面不能有任何输出)
<?php if(isset($_POST["submit"])){ $payment = $_POST["payment"]; if ($payment == "cash") { header("Location: http://localhost/Ecommerce-app-h/congrats.php"); exit(); } else { header("Location: cart.php"); exit(); } } ?>
页面HTML内容
<div id="paymentmethod" style="margin-bottom:50px;"> <h4 style="font-weight: bold; color: #0C7D53;">Payment Method </h4> <form action="" method="post"> <label style="padding-top:8px;">Choose your payment method:</label> <!-- 新增name="payment"属性,确保表单提交时传值 --> <select id="payment" name="payment" class="form-control"> <option value="cash">Cash</option> <option value="paypal">PayPal</option> </select> <p><br/></p> <center><input style="width:25%;" type="submit" name="submit" value="Checkout" class="btn btn-primary btn-lg"> </center> </form> <p><br/></p> </div>
内容的提问来源于stack exchange,提问作者Turtle Developer
相关产品推荐
相关产品推荐

