我想通過 fetch API 將單擊按鈕時的表單發送到我驗證表單的 index.php。如果表單中沒有錯誤,我想用 PHPMailer 向客戶端發送一封電子郵件。由于某種原因,客戶沒有收到電子郵件。我已經搜索了幾個小時來尋找答案,但無法解決問題。這是 JavaScript 代碼: const form = document.querySelector("#myForm"); 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"); //showing error 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("You succesfully bought the product!"); //window.location.replace("index.html"); //if there was no error redirect to index.html } }); })
1 回答

繁花如伊
TA貢獻2012條經驗 獲得超12個贊
首先,您將導入PHPMailer 的版本5 和 6!事情不會那么順利;繼續 6. 刪除這些行及其指向的文件;你不需要它們:
require?'PHPMailerAutoload.php'; require?"class.phpmailer.php"; require?"class.smtp.php";
如果您對如何導入庫感到困惑,那么現在是學習Composer 的好時機。
奇怪的是,當您注釋掉顯示錯誤所在的代碼時,當出現錯誤時它不再顯示...該console.log(text);
行也應該顯示瀏覽器所看到的內容。
解決這個問題的最佳方法是一次調試一件事。
首先確保您的表單實際上以應有的格式將數據傳遞到您的腳本 - 考慮到 JSON 錯誤(不是來自 PHPMailer),情況似乎很可能并非如此,而這可能就是來源你所有的問題。因此,將其添加到腳本頂部附近:
var_dump($_REQUEST);
這將破壞您的 ajax 請求(因為輸出不是 JSON),但您將能夠在瀏覽器的 Web 檢查器中看到原始響應。
確認其格式正確并包含所有預期的表單數據后,刪除該var_dump
行并繼續檢查您是否正確訪問 JSON 中的屬性。同樣,您可能會發現最好在瀏覽器的檢查器中顯示它。一旦您確定以正確的方式提取了所需的所有數據,就可以繼續發送電子郵件。
考慮到通過 SMTP 使用 gmail 的常見問題,最好使用固定值測試您的電子郵件代碼,與您的 ajax 內容分開 - 如果沒有其他內容妨礙,它本身就很難調試。
現在您已經到了所有各個部分都可以工作的地步,將它們重新組合在一起并檢查每個步驟。
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消