首页 > 解决方案 > 在 PHP 中调用 POST 操作后如何保持在同一页面上

问题描述

我有一个简单的在线表单,它在提交时调用 PHP 脚本。

<form name="newform" id="regForm" action="../includes/submit.inc.php" method="post">

单击提交按钮时,浏览器中的站点 URL 更改为http://example.com/includes/submit.inc.php并且页面为空白。

我想在提交表单后显示一条感谢消息,并且我希望 URL 保持http://example.com

我尝试使用 JS 隐藏我网站的主容器并启用带有感谢消息的 DIV。

function submit() {
    document.getElementById("main").style.display = "none";
    document.getElementById("success").style.display = "inline";
}

document.getElementById('regForm').onsubmit = function () {
    var terms = document.getElementById('consentBox');

    if (!terms.checked) {
        showWarnings(warnings);
        return false;
    }
    submit();
    return true;
    
};

这种作品我可以在一瞬间看到感谢消息,但随后浏览器转到http://example.com/includes/submit.inc.php并且页面为空白。我真的想避免重定向到另一个 .php 文件。我知道我可以做这样的事情:

header( "location: ../success.php", true, 301 );

但更喜欢在同一页面上显示消息。我怎样才能做到这一点?

提前致谢。

标签: javascriptphp

解决方案


这可以通过使用 AJAX 和表单的序列化来实现。这是假设 php 脚本在成功完成后返回状态消息(要显示的 html 块)。如果 php 脚本中存在问题,这也有助于错误处理。此示例使用jQuery 库

<form name="myForm" id="myForm">
  <input type="text" name="input1">
  <input type="text" name="input2">
</form>
// Using jQuery 

$('#myForm').submit(function(e) {

  //Prevent Default
  e.preventDefault();

  // Gather Form Values into Array  
  var values = {};
  $.each($('#myForm').serializeArray(), function(_, kv) {
    values[kv.name] = kv.value;
  });

  $.ajax({
      method: "POST",
      url: "pathToFile/formHandlingFile.php",
      dataType: "html",
      data: {
        vals: values
      }
    })
    .done(function(data) {
     
     $('#main').hide()
     $('#success').html(data)
     $('#success').show()

    })

});

推荐阅读