PHP调用mail()发信时如何通过JS/PHP实现Sending...加载提示
解决方案分步实现
方案1:优先推荐的异步Ajax方案(无页面刷新,体验更好)
第一步:修改前端按钮与提示容器代码
替换原有a标签,提前预留加载提示容器:
<!-- 替换原有a标签,取消默认跳转行为 --> <a id="resetPassBtn" class="button_link_small" href="javascript:;">Reset password</a> <!-- 加载提示容器,默认隐藏 --> <div id="sendingTip" style="display: none; padding: 10px 0;"> <img src="https://i.sstatic.net/nd37W.png" alt="发送中"> 请等待邮件发送中... </div>
第二步:添加前端交互JS逻辑
点击按钮先显示加载提示,再异步请求重置接口:
document.getElementById('resetPassBtn').addEventListener('click', function() { const sendTip = document.getElementById('sendingTip'); // 显示加载提示、禁用按钮防重复点击 sendTip.style.display = 'block'; this.disabled = true; this.style.pointerEvents = 'none'; this.style.opacity = '0.6'; // 拼接请求参数发起异步请求 const postId = '<?php echo $getPostID; ?>'; fetch(`edit.php?change=user&step=edit&postid=${postId}&ResetUserPass&req=true`) .then(res => res.text()) .then(() => { // 发送成功修改提示 sendTip.innerText = '密码重置邮件已发送,请查收您的邮箱'; setTimeout(() => { sendTip.style.display = 'none'; this.disabled = false; this.style.pointerEvents = 'auto'; this.style.opacity = '1'; }, 3000); }) .catch(() => { sendTip.innerText = '邮件发送失败,请稍后重试'; }); });
该方案不需要修改原有PHP后端逻辑,原有功能可直接复用。
方案2:同步请求兼容方案(无需改前端交互,仅调整PHP代码)
你的原逻辑是同步跳转,服务端默认会等所有逻辑执行完成后才返回完整响应,所以echo的内容不会提前展示,需要手动关闭输出缓存强制提前输出内容:
if($getreq == 'true') { // 关闭输出缓存,强制实时输出内容 ob_end_clean(); ob_implicit_flush(true); // 输出加载提示,额外填充空白字符触发浏览器渲染(部分浏览器需要收到至少256字节才会开始渲染页面) echo '<div style="padding: 20px;"><img src="https://i.sstatic.net/nd37W.png" alt="发送中"> 请等待邮件发送中...</div>'; echo str_repeat(' ', 256); flush(); // 保留原有发邮件逻辑 $headers = "MIME-Version: 1.0" . "\r\n"; $headers = "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers = 'FROM: <BLANK>'; $recipient = $getusermail; $subject = "Password reset"; $message = "Password has been reset"; mail($recipient, utf8_decode($subject), utf8_decode($message), $headers); // 发送完成后跳转或者输出成功提示 echo '<script>alert("邮件发送成功");location.href="edit.php?change=user&step=edit&postid='.$getPostID.'";</script>'; exit; }
注意该方案兼容性受服务器配置影响,部分托管服务器可能禁用了输出缓存控制权限,优先选择方案1。
内容的提问来源于stack exchange,提问作者MauiRiis
相关产品推荐
相关产品推荐

