AJAX提交联系表单时直接显示PHP默认状态消息是什么原因?
问题成因
- JS事件绑定完全失效:原生DOM元素没有
.submit(回调函数)这种写法,这是jQuery专属API,你未引入jQuery的前提下这个绑定根本不生效,表单提交时会触发默认跳转行为,直接跳转到后端PHP地址,就会显示PHP输出的JSON字符串,也就是你看到的白屏内容。 - AJAX逻辑不完整:既没有调用
xhr.send()发送请求数据,也没有序列化表单数据;同时你设置了请求头为application/json,但PHP默认的$_POST只能解析application/x-www-form-urlencoded格式的请求,就算请求发出去后端也拿不到表单参数。 onreadystatechange逻辑有误:readyState从1到3的变化都会触发回调,只要还没到4且200的状态就会先显示错误提示,后续就算请求成功也会出现提示闪烁的问题。
修复方案
1. 替换为正确的原生JS代码
document.addEventListener('DOMContentLoaded', function() { const contactForm = document.getElementById('contact-form'); // 原生绑定submit事件必须使用addEventListener contactForm.addEventListener('submit', function(e) { // 阻止表单默认提交跳转行为 e.preventDefault(); const xhr = new XMLHttpRequest(); const url = 'contactform3.php'; xhr.open('POST', url, true); // 使用表单默认编码格式,PHP才能通过$_POST正常获取参数 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { // 仅处理请求完成的状态 if (xhr.readyState == 4) { if (xhr.status == 200) { let jsonData = JSON.parse(xhr.response); console.log(jsonData); contactForm.reset(); // 直接使用后端返回的提示消息,无需写死 document.querySelector('.response').innerHTML = jsonData.message; } else { document.querySelector('.response').innerHTML = 'Er is iets misgegaan.'; } } }; // 序列化表单数据 const formData = new FormData(contactForm); const params = new URLSearchParams(formData).toString(); // 发送请求 xhr.send(params); }) })
2. PHP代码优化(可选,建议添加)
可以在输出JSON前添加响应头,同时对参数判空做兼容,避免报错:
<?php // 收件人邮箱 $toEmail = 'info@example.com'; $status = 0; $statusMsg = 'Er is iets misgegaan.'; if(isset($_POST['contact_submit'])){ // 获取提交的表单数据,空值默认设为空字符串避免报错 $assignmentchoice = $_POST['assignmentchoice'] ?? ''; $projectchoice = $_POST['projectchoice'] ?? ''; $name = $_POST['name'] ?? ''; $lastname = $_POST['lastname'] ?? ''; $email = $_POST['email'] ?? ''; $tel = $_POST['tel'] ?? ''; $address = $_POST['address'] ?? ''; $zip = $_POST['zip'] ?? ''; $message = $_POST['message'] ?? ''; if(!empty($assignmentchoice) && !empty($projectchoice) && !empty($name) && !empty($lastname) && !empty($email) && !empty($message)) { if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) { $statusMsg = 'Vul een geldig e-mail adres in.'; } else { $emailSubject = 'U heeft een nieuw bericht van'.$name; $htmlContent = '<h2>Je hebt een nieuw bericht</h2> <h4>Opdracht:</h4><p>'.$assignmentchoice.'</p> <h4>Project:</h4><p>'.$projectchoice.'</p> <h4>Naam:</h4><p>'.$name.'</p> <h4>Achternaam:</h4><p>'.$lastname.'</p> <h4>Email adres:</h4><p>'.$email.'</p> <h4>Telefoonnummer:</h4><p>'.$tel.'</p> <h4>Adres locatie:</h4><p>'.$address.'</p> <h4>Postcode locatie:</h4><p>'.$zip.'</p> <h4>Bericht:</h4><p>'.$message.'</p>'; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= 'From: '.$name.'<'.$email.'>'. "\r\n"; $sendEmail = mail($toEmail, $emailSubject, $htmlContent, $headers); if($sendEmail) { $status = 1; $statusMsg = 'Bedankt voor uw bericht. Wij nemen zo snel mogelijk contact met u op.'; } else { $statusMsg = 'Er is iets misgegaan.'; } } } else { $statusMsg = 'Vul alstublieft alle velden in.'; } } // 添加JSON响应头,方便前端解析返回数据 header('Content-Type: application/json'); $response = array( 'status' => $status, 'message' => $statusMsg ); echo json_encode($response); ?>
内容的提问来源于stack exchange,提问作者Maurice Markslag
相关产品推荐
相关产品推荐

