javascript - 在 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 );
但更喜欢在同一页面上显示消息。我怎样才能做到这一点?
提前致谢。
解决方案
这可以通过使用 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()
})
});
推荐阅读
- plsql - 在字符串中分配 '
- php - C:\xampp\htdocs\org1\wp-settings.php 中没有这样的文件或目录
- unit-testing - Flutter/Dart 在单元测试中等待几秒钟
- kiwi-tcms - 由于 ssl 配置,我猜在使用 docker 运行 kiwi 后无法访问服务
- r - R 插入符号:结合 rfe() 和 train()
- c# - 如何在 ASP.NET Core 2.1 网站上启用 HttpOnly cookie
- .net - 如何使用“DetectLocalizedObjects”?
- codeigniter - codeigniter 在单独的字段中上传 2 个文件(图像和视频)
- html - 使用uikit的图像叠加悬停效果
- java - 通过 EventChannel 向 Flutter 发送 Android SMS BroadcastReceiver 数据