当客户订购产品时,他们会向服务器端发送一个表单。我在 php 中验证表单,如果没有错误,我会向客户发送电子邮件,并向自己发送一封电子邮件,其中包含从表单收到的产品信息。我使用 PHPMailer 发送电子邮件,但它相当慢,发送邮件并从服务器返回 javascript 的响应需要大约 5 秒。当我取出发送电子邮件的代码时,回复立即到达。PHPMailer 的响应速度变慢,但我不知道为什么。
JavaScript:
const form = document.querySelector("#form");
form.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(form);
fetch("index.php", {
method: 'post',
body: formData
}).then((resp) => resp.json())
.then(function (text) {
console.log(text); //Do something with the response, which is an array
if(text !== undefined && text.length > 0) { //The array isn't empty
//Show errors
const formdiverror = document.querySelector(".col-100-form-error");
const colform = document.querySelector(".col-100-form");
colform.style.display = "block";
formdiverror.innerHTML = "";
text.forEach(t => formdiverror.innerHTML += t + "</br>");
} else {
//array is empty, no errors
const colform = document.querySelector(".col-100-form");
if(colform !== null || colform !== undefined) colform.style.display = "none";
alert("Success!");
window.location.replace("index.html"); //if there was no error redirect to index.html
}
});
})
如果验证中出现错误,我会echo json_encode($errors);
发送回错误并在客户端显示它们。如果没有错误我使用echo json_encode([]);
. 在 javascript 中,我检查获取响应。如果它是一个空数组,则没有错误,我可以重定向到index.html。
函数式编程