當客戶訂購產(chǎn)品時,他們會向服務(wù)器端發(fā)送一個表單。我在 php 中驗證表單,如果沒有錯誤,我會向客戶發(fā)送電子郵件,并向自己發(fā)送一封電子郵件,其中包含從表單收到的產(chǎn)品信息。我使用 PHPMailer 發(fā)送電子郵件,但它相當慢,發(fā)送郵件并從服務(wù)器返回 javascript 的響應需要大約 5 秒。當我取出發(fā)送電子郵件的代碼時,回復立即到達。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 } }); })如果驗證中出現(xiàn)錯誤,我會echo json_encode($errors);發(fā)送回錯誤并在客戶端顯示它們。如果沒有錯誤我使用echo json_encode([]);. 在 javascript 中,我檢查獲取響應。如果它是一個空數(shù)組,則沒有錯誤,我可以重定向到index.html。
Javascript fetch API 和 PHPMailer 響應緩慢
ibeautiful
2023-09-22 16:08:03