如何实现Bootstrap 5.2表单邮件发送成功后显示绿色Alert
需求说明
我制作了一个联系表单,所有功能正常,能按预期接收邮件。现在希望在邮件发送成功后,在表单位置显示Bootstrap 5.2的绿色成功Alert组件,而非当前跳转至显示“success”的页面。
以下是现有代码:
contact.php
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; if(isset($_POST["send"])){ $body = $_POST['message']; $name = $_POST['name']; $phone = $_POST['phone']; $email = $_POST['email']; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'mymail@gmail.com'; $mail->Password = 'password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption $mail->Port = 465; $mail->setFrom('mymail@gmail.com'); $mail->addAddress($_POST["email"]); $mail->isHTML(true); $mail->Subject = 'Projet web'; $mail->Body = "Message:" . $body . "<br>Phone number: " . $phone . "<br>Name: " . $name . "<br>Mail: " . $email; $mail->send(); echo "success"; }
index.php
<div class="col-md-4 mb-3 mb-md-0" data-aos="fade-left"> <form id="contactForm" action="contact.php" method="POST"> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1"><i class="bi bi-person-fill"></i></span> <input type="text" id="name" name="name" class="form-control" placeholder="Nom Prénom" aria-label="Nom Prénom" aria-describedby="basic-addon2" required> </div> <!-- Email address input --> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1">@</span> <input type="text" id="email" name="email" class="form-control" placeholder="Email" aria-label="email" aria-describedby="basic-addon1" required> </div> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1"><i class="bi bi-telephone-fill"></i></span> <input type="text" id="phone" name="phone" class="form-control" placeholder="Téléphone" aria-describedby="basic-addon2" required> </div> <!-- Message input --> <div class="mb-3"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Decrivez le plus possible votre projet" name="message" required></textarea> </div> <!-- Form submit button --> <div class="d-grid"> <button class="btn btn-primary btn-lg" name="send" type="submit">Submit</button> </div> </form> </div>
实现步骤
要实现无刷新显示成功提示,需要用AJAX异步提交表单,同时修改后端返回结构化数据,具体操作如下:
1. 优化后端contact.php
修改后端代码,添加异常处理,并返回JSON格式的结果,方便前端判断状态:
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; // 设置返回JSON格式的响应头 header('Content-Type: application/json'); if(isset($_POST["send"])){ try { $body = $_POST['message']; $name = $_POST['name']; $phone = $_POST['phone']; $email = $_POST['email']; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'mymail@gmail.com'; $mail->Password = 'password'; // 注意:建议用应用专用密码而非账号原密码 $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mail->Port = 465; $mail->setFrom('mymail@gmail.com'); $mail->addAddress($email); $mail->isHTML(true); $mail->Subject = 'Projet web'; $mail->Body = "Message:" . $body . "<br>Phone number: " . $phone . "<br>Name: " . $name . "<br>Mail: " . $email; $mail->send(); // 返回成功状态 echo json_encode(['status' => 'success', 'message' => '邮件发送成功!']); } catch (Exception $e) { // 返回失败状态及错误信息 echo json_encode(['status' => 'error', 'message' => '邮件发送失败:' . $mail->ErrorInfo]); } }
2. 修改前端index.php
- 添加Alert容器(默认隐藏)
- 编写JavaScript代码,监听表单提交事件,用Fetch API异步发送请求,并根据响应显示提示:
<div class="col-md-4 mb-3 mb-md-0" data-aos="fade-left"> <!-- 成功提示Alert,默认隐藏 --> <div id="successAlert" class="alert alert-success alert-dismissible fade show" role="alert" style="display: none;"> 邮件发送成功! <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <!-- 错误提示Alert,默认隐藏 --> <div id="errorAlert" class="alert alert-danger alert-dismissible fade show" role="alert" style="display: none;"> <span id="errorMsg"></span> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <form id="contactForm" action="contact.php" method="POST"> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1"><i class="bi bi-person-fill"></i></span> <input type="text" id="name" name="name" class="form-control" placeholder="Nom Prénom" aria-label="Nom Prénom" aria-describedby="basic-addon2" required> </div> <!-- Email address input --> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1">@</span> <input type="text" id="email" name="email" class="form-control" placeholder="Email" aria-label="email" aria-describedby="basic-addon1" required> </div> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1"><i class="bi bi-telephone-fill"></i></span> <input type="text" id="phone" name="phone" class="form-control" placeholder="Téléphone" aria-describedby="basic-addon2" required> </div> <!-- Message input --> <div class="mb-3"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Decrivez le plus possible votre projet" name="message" required></textarea> </div> <!-- Form submit button --> <div class="d-grid"> <button class="btn btn-primary btn-lg" name="send" type="submit">Submit</button> </div> </form> </div> <script> document.getElementById('contactForm').addEventListener('submit', async function(e) { // 阻止表单默认提交行为 e.preventDefault(); // 隐藏所有提示框 document.getElementById('successAlert').style.display = 'none'; document.getElementById('errorAlert').style.display = 'none'; // 收集表单数据 const formData = new FormData(this); try { // 发送异步请求 const response = await fetch('contact.php', { method: 'POST', body: formData }); const result = await response.json(); if (result.status === 'success') { // 显示成功提示 document.getElementById('successAlert').style.display = 'block'; // 重置表单 this.reset(); } else { // 显示错误提示 document.getElementById('errorMsg').textContent = result.message; document.getElementById('errorAlert').style.display = 'block'; } } catch (error) { // 处理网络错误 document.getElementById('errorMsg').textContent = '请求失败,请稍后重试'; document.getElementById('errorAlert').style.display = 'block'; } }); </script>
3. 注意事项
- 确保Bootstrap 5.2的CSS和JS已经正确引入到页面中(需包含
bootstrap.bundle.js,以支持Alert关闭按钮的data-bs-dismiss属性) - Gmail SMTP建议使用应用专用密码(开启2FA后生成),而非账号原密码,避免账号安全风险
- 可根据需求调整Alert的样式或提示文案
内容的提问来源于stack exchange,提问作者xajetin
相关产品推荐
相关产品推荐

