如何在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 );

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

提前感谢。

您可以在编写主代码的页面中添加post php代码。例如,

<form name="newform" id="regForm" action="inex.php" method="post">
<?php
//and your php post code here 
?>

这可以通过使用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()
})
});