You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS表单验证完成后调用PHP文件及跳转等待问题排查

联系表单JS与PHP结合的跳转问题

我正在为个人作品集网站开发联系表单,已分别实现可用的PHP表单与JavaScript验证功能,但将二者结合时出现异常。最初需求为所有输入验证通过后调用contactForm.php,尝试使用XMLHttpRequest实现但未成功;更新代码后可正常发送邮件,但存在JavaScript直接跳转页面、不等待PHP执行完成的问题。表单位于网站底部。

12月29日更新
更新代码后已能正常发送邮件,但存在JavaScript不等待PHP文件执行完成就直接跳转到成功页面的问题。

初始JS验证代码

function formValidator(){
  const form = document.getElementById('form');
  const name = document.getElementById('name');
  const email = document.getElementById('email');
  const message = document.getElementById('message');
  let errorStatus = true;

  form.addEventListener('submit',(e) => {
    e.preventDefault(); // 阻止默认提交行为
    checkInputs(); // 验证输入内容
    if(errorStatus == true){ // 验证通过则执行
      console.log("验证通过")
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() 
      {
          if (xhttp.readyState == 4 && xhttp.status == 200) {
                  document.getElementById("result").innerHTML = xhttp.responseText;}
      };
      xhttp.open("POST", "contactForm.php", true);
      xhttp.send();
    } 

else{
      form.scrollIntoView({ behavior: 'smooth'});
      }
  });

  function checkInputs(){
    const nameValue = name.value.trim();
    const emailValue = email.value.trim();
    const messageValue = message.value.trim();

    if(nameValue === ''){
      setErrorFor(name, "Proszę podać imię");

    } else{
      setSuccessFor(name);
    }
  }

  function setErrorFor(input, message){
    const formControl = input.parentElement;
    const errorContent = formControl.querySelector('.error-message');
    const alertVisibility = formControl.querySelector('.alert');

    errorContent.innerText = message;
    alertVisibility.style.visibility = "visible";

    errorStatus = false;
  }

  function setSuccessFor(input){
    const formControl = input.parentElement;
    const alertVisibility = formControl.querySelector('.alert');

    alertVisibility.style.visibility = "hidden";

    errorStatus = true;
  }
}

尝试添加的XMLHttpRequest代码

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() 
{
    if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", "contactForm.php", true);
xhttp.send();

contactForm.php代码

<?php
// 获取表单数据 
$name = $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];

$to = "piotr.brze95@gmail.com";
$subject = "Nowe zlecenie od " . $name . " z strony MelonStudio";

// 邮件内容
$txt ="Name = ". $name . "\r\n  Email = "
    . $email . "\r\n Message =" . $message;

$headers = "From: noreply@demosite.com";
if($email != NULL) {
    mail($to, $subject, $txt, $headers);
}
?>

更新后的JS代码(存在跳转问题)

e.preventDefault();
checkInputs();

if(errorStatus === true){
  console.log("验证通过");
  phpFetcher();
  window.location.href = "https://melon.studio/success-page.html";

} else{
form.scrollIntoView({ behavior: 'smooth'});
}
});
function phpFetcher(){
form.addEventListener('click', function(event){
    const formattedFormData = new FormData(form);
    postData(formattedFormData);
});

async function postData(formattedFormData){
    const response = await fetch('contactForm.php',{
        method: 'POST',
        body: formattedFormData
    });
}

内容的提问来源于stack exchange,提问作者dzm11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:15:52