【发布时间】:2021-11-10 06:24:56
【问题描述】:
我有一个简单的表格
<!DOCTYPE html>
<html>
<head>
<script>
//prevents website to send another POST request when user refreshes website
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
</head>
<body>
<div class="content">
<form method="post">
<label>StudentID : </label>
<input type="text" name="studentid">
<p id="errorMessage"></p>
<input type="submit" value="Book Meeting">
</form>
</div>
</body>
</html>
还有我的 php 代码的简短 sn-p:
<?php
//must be connected to the database before running the website
require_once("connection.php");
//if the form is submitted(to search for student id)
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$studentid = $_POST['studentid'];
//if the input is not empty
if(!empty($studentid))
{
每当我尝试使用任何输入提交表单时,if($_SERVER['REQUEST_METHOD'] == "POST") 不会检测到 POST 方法,但是当我使用空输入提交表单时它可以工作。我整晚都在调试,但仍然无法找出问题所在。任何帮助将不胜感激!
【问题讨论】:
-
这没有任何意义。是否提交数据不会影响表单提交的 http 方法。即使字段为空,它仍会发送 POST。您究竟是如何检查这种行为的?它只会在您第一次加载表单时发送 GET,而不是在您提交时发送它
-
@ADyson 我尝试在
if($_SERVER['REQUEST_METHOD'] == "POST")之前和之后插入echo 语句,以发现如果我提交带有输入的字段,php 不会输入if 语句。 -
执行
var_dump($_SERVER);(在第一个 if 语句之前)并检查它的内容。另外,“防止网站在用户刷新网站时发送另一个POST请求”最好通过在服务器上执行Post-Redirect-Get方法而不是在客户端处理它。 -
首先,尝试删除干扰历史的 JavaScript。之后问题是否仍然存在?如果是这样,请密切关注浏览器开发工具的网络面板中发生的情况。
-
感谢 MagnusEriksson 和 CBroe 删除 javascript sn-p 后它似乎可以工作,我将尝试在服务器端实现 PRG。