使用AJAX实现PHP联系表单提交后同页无刷新显示消息提示
无刷新提交表单解决方案
你可以通过AJAX异步提交的方式实现提交后不跳转、在当前页展示提示的需求,不需要引入第三方依赖,直接修改原有两处代码即可:
第一步:修改index.html代码
你需要在表单下方新增提示信息容器,再添加一段JS代码监听表单提交行为,阻止默认跳转逻辑,异步提交表单数据:
<div class="main"> <div class="info">Give Your Feedback!</div> <form action="mail_handler.php" method="post" name="form" class="form-box"> <label for="name">Name</label><br> <input type="text" name="name" class="inp" placeholder="Enter Your Name" required><br> <label for="email">Email ID</label><br> <input type="email" name="email" class="inp" placeholder="Enter Your Email" required><br> <label for="phone">Phone</label><br> <input type="tel" name="phone" class="inp" placeholder="Enter Your Phone" required><br> <label for="message">Message</label><br> <textarea name="msg" class="msg-box" placeholder="Enter Your Message Here..." required></textarea><br> <input type="submit" name="submit" value="Send" class="sub-btn"> </form> <!-- 新增提示信息容器 --> <div id="form-message" style="margin-top: 15px; display: none;"></div> </div> <script> // 监听表单提交事件 document.querySelector('.form-box').addEventListener('submit', function(e) { // 阻止表单默认跳转提交行为 e.preventDefault(); const form = this; const msgBox = document.getElementById('form-message'); const submitBtn = form.querySelector('.sub-btn'); // 提交过程中禁用按钮防止重复提交 submitBtn.disabled = true; submitBtn.value = '发送中...'; // 异步提交表单数据 fetch(form.action, { method: form.method, body: new FormData(form) }) .then(response => response.json()) .then(res => { // 显示提示信息 msgBox.style.display = 'block'; if(res.status === 'success') { msgBox.style.color = '#2ecc71'; form.reset(); // 提交成功清空表单 } else { msgBox.style.color = '#e74c3c'; } msgBox.innerText = res.message; // 恢复按钮状态 submitBtn.disabled = false; submitBtn.value = 'Send'; // 3秒后自动隐藏提示 setTimeout(() => { msgBox.style.display = 'none'; }, 3000); }) .catch(() => { // 处理网络异常情况 msgBox.style.display = 'block'; msgBox.style.color = '#e74c3c'; msgBox.innerText = '网络异常,请稍后重试'; submitBtn.disabled = false; submitBtn.value = 'Send'; }); }); </script>
第二步:修改mail_handler.php代码
调整PHP返回格式为JSON,方便前端识别提交状态和展示提示:
<?php // 设置返回格式为JSON header('Content-Type: application/json'); if(isset($_POST['submit'])){ $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $msg = $_POST['msg']; $to = 'mehrdad3373@gmail.com'; // 替换为你的实际收件邮箱 $subject = 'Form Submission'; $message = "Name :".$name."\n"."Phone :".$phone."\n"."Wrote the following :"."\n\n".$msg; $headers = "From: ".$email; if(mail($to, $subject, $message, $headers)){ echo json_encode([ 'status' => 'success', 'message' => "发送成功!感谢您".$name.",我们会尽快与您联系!" ]); } else{ echo json_encode([ 'status' => 'error', 'message' => "发送失败,请稍后重试" ]); } } ?>
如果需要保留英文提示,直接修改PHP代码中message字段的内容即可。
内容的提问来源于stack exchange,提问作者Mehrdad Hosseini
相关产品推荐
相关产品推荐

