【问题标题】:How to stop a form redirection after displaying an error message in PHP?在 PHP 中显示错误消息后如何停止表单重定向?
【发布时间】:2017-02-11 19:10:26
【问题描述】:

如何避免在以下情况下重新提交表单 - 我的 HTML 文件有一个表单,该表单将数据发送给自身以进行验证。包含在同一页面中,<!DOCTYPE html> 标记之前是必需的 PHP 语句。这将获取名为process.php 的文件的内容并检查用户数据。如果数据不正确,则它成功显示错误消息。如果数据正确,它会发送一封电子邮件。 - 这一切都很好,但是如果用户返回“按下后退箭头”并刷新页面,那么它会要求重新发送数据。我该如何避免这个问题。

<?php require("inc/process.php"); end(); ?>
<!DOCTYPE html>
<html>
 <head>
 <title>Page one</title>
 </head>
 <body>

   <div class="form-box">

   <!--Display error message PHP-->
   <?php
    if (isset($error_msg)) {
     $show_error = "<p class='error-message'>" . $error_msg . "</p>";
     echo strip_tags($show_error, '<p>');
    }
    ?>

    <form method="post" action="index.html">
     <input name="full-name" type="text">
     <input name="email" type="email">
    </form>

   </div> 


 </body>
</html>

【问题讨论】:

  • 我可能是错的,但这是正常行为。为什么不在客户端也实施验证,而不是找到解决此问题的方法?如果表单无效,则不会将表单发送到服务器。如果有人试图“破解”您的表单验证,服务器将触发异常,因为它已经完成了。例如,您可以将属性 required 添加到必需的 input(如年龄)
  • 好的,这是个好建议。如何停止将表单数据发送到服务器?
  • 您不必“停止”发送数据。浏览器会自动为您管理。例如,您希望填写除年龄以外的所有字段。所以你可以在你的所有字段&lt;input name="First-name" class="first-name" type="text" placeholder="First name" required&gt;//required added 上尝试类似的东西。关于字段年龄,您可以禁用它&lt;input name="age" class="age" type="text" placeholder="Please leave blank" disabled&gt; //disabled added。更多关于输入标签的信息在这里w3schools.com/TAgs/tag_input.asp
  • 我不希望使用 HTML 验证,因为它可以由用户更改。这有点安全风险。
  • 不,因为您还保留了服务器端的验证。而不是向服务器发送无效数据并返回错误。这将防止发送无效数据,如果有人破解它,就像我在第一篇文章中所说的那样,服务器验证将阻止表单验证。它也是用户友好的,因为您的用户不必等待服务器响应,他们将直接在浏览器中看到该字段无效。这就是现代网站的运作方式。无论如何,这只是一个建议,如果你不想这样做,决定权在你:)

标签: php validation submission


【解决方案1】:

最好使用jquery ajax,例如:

$("#FormID").submit(function(e) {

var url = "path/to/your/script.php"; // the script where you handle the form input.

$.ajax({
       type: "POST",
       url: url,
       data: $("#FormID").serialize(), // serializes the form's elements.
     })

  // when the request is succesfull
  .done(function( data ) {
    alert(data); // show response from the php script.
  })

  // when an error occurs
  .fail(function() {
    alert( "error" );
  });

e.preventDefault(); // avoid to execute the actual submit of the form. (no redirection)

});

【讨论】:

    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2015-09-13
    • 2020-12-01
    • 2015-06-19
    • 2012-02-15
    相关资源
    最近更新 更多