【问题标题】:HTML form does not fire POST method if it is submmited with input如果 HTML 表单通过输入提交,则不会触发 POST 方法
【发布时间】: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。

标签: php html


【解决方案1】:

好像是javascript代码

//prevents website to send another POST request when user refreshes website
if ( window.history.replaceState ) {
   window.history.replaceState( null, null, window.location.href );
}

按照 CBroe 和 Magnus 的建议,正在干扰我来自 HTML 表单的 POST 请求。

PRG method 将按照 Magnus 的建议在服务器端而不是客户端实现。

【讨论】:

  • 这有一个有用的答案,@Boom 的特点。它清楚地引用了有问题的片段,并提供了指向另一个阐明理论的线程的链接。请记住,您今天的答案将在您当前的问题/问题之外的未来看到,并且它们越具体和有用,它们对未来的开发人员的帮助就越大。继续努力!
【解决方案2】:

$_SERVER['REQUEST_METHOD'] 返回GET,因为您正在通过浏览器请求网页。轻松检查输入数据的最简单方法是:

<?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( isset( $_POST['studentid'] ) and !empty( $_POST['studentid'] ) )
    {

        $studentid = $_POST['studentid'];

【讨论】:

  • 为什么它返回 GET 呢?我已在 html 表单上将方法设置为 POST。
猜你喜欢
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 2018-09-17
  • 2019-04-27
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多