猿问

Javascript fetch API 和 PHPMailer 响应缓慢

当客户订购产品时,他们会向服务器端发送一个表单。我在 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。



ibeautiful
浏览 119回答 1
1回答

函数式编程

这很可能是因为 SMTP 通常很慢(有时是故意的),尤其是在与远程服务器通信时。在页面/请求处理期间发送根本不适合 SMTP,但这并不能阻止很多人这样做。使其更快的最佳方法是通过本地邮件服务器进行中继。这样就没有网络开销,并且响应时间会非常快——每秒发送数百条消息应该没有问题。它还将为您处理排队、限制、重试等问题。
随时随地看视频慕课网APP
我要回答