PHP 联系表单脚本不会页面重定向



此php代码通过电子邮件将表单内容发送给预期收件人。我想我可以在下面的脚本中以某种形式进行后期处理(也许是js页面重定向)。就像在";在提交表格之后做一些事情">我试过了,效果很好

<!-- (B) AJAX SUBMISSION -->
<script>
function doajax () {
// (B1) GET FORM DATA
var data = new FormData(document.getElementById("cform"));
// REQUIRED: APPEND CAPTCHA RESPONSE
data.append("g-recaptcha-response", grecaptcha.getResponse());
// (B2) AJAX FETCH
fetch("process.php", { method: "POST", body: data })
.then((res) => { alert ('message sent'); window.location.href = "index.php"; })
});
return false;
}
</script>

HTML:

<form id="cform" method="post" onsubmit="return doajax();">
<input type="text" name="name" required/>
<input type="email" name="email" required/>
<textarea name="message" required></textarea>
<div class="g-recaptcha" data-sitekey="--- SITE KEY ---></div>
<input type="submit" id = "submit" value="Submit"/>
</form>

process.php

<?php
// (B) VERIFY CAPTCHA 
$secret = "---google recaptcha secret ---"; 
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=".$_POST["g-recaptcha-response"];
$verify = json_decode(file_get_contents($url));
if (!$verify->success) { $error = "Invalid captcha"; }
// (C) SEND MAIL
$mailTo = "me@gmail.com"; 
$mailSubject = "Contact Form";
$mailBody = "";

foreach ($_POST as $k=>$v) {
if ($k!="g-recaptcha-response") { $mailBody .= "$k: $vrn"; }
}
if (!@mail($mailTo, $mailSubject, $mailBody)) { $error = "Failed to send mail";}
?>

而不是像您包含的那样向浏览器编写代码:

echo "<script>alert('Successfully sent'); window.location = './index.php';</script>";
exit;

尝试用PHP替换上面的内容,通过设置标题来进行重定向:

header('Location: https://www.google.com');

请注意,这需要页面上以前没有输出,因为在HTML输出开始后无法设置标题。

有关PHP重定向的更多信息,请查看以下答案:如何在PHP中进行重定向?

最新更新