PHPMailer邮件表单发送后,跳转页面时如何显示提示弹窗?
问题描述
我基于PHPMailer开发了邮件联系表单,希望在发送邮件后显示提示弹窗,同时跳转到contacto.php页面。但目前仅移除header跳转语句时弹窗可正常显示,添加跳转后弹窗失效,请问该如何解决?
对应的代码:
<?php //PHPMailer first part of the code try { //PHPMailer second part of the code $mail->send(); header('Location: contacto.php'); $message = "Mail sent"; echo "<script type='text/javascript'>alert('$message');</script>"; } catch (Exception $e) { echo "Error al enviar: {$mail->ErrorInfo}"; header('Location: contacto.php'); $message1 = "Mail not sent"; echo "<script type='text/javascript'>alert('$message1');</script>"; }
解决方法
问题核心是:PHP的header('Location: ...')会立即通知浏览器跳转,后续的echo代码根本不会被浏览器执行,所以弹窗自然无法显示。下面是两种可行的解决方式:
方式一:用JavaScript实现弹窗+跳转
直接移除PHP的重定向代码,改用JS先弹出提示,用户关闭弹窗后再跳转页面:
<?php //PHPMailer first part of the code try { //PHPMailer second part of the code $mail->send(); $message = "Mail sent"; echo "<script type='text/javascript'>alert('$message'); window.location.href='contacto.php';</script>"; exit; // 终止后续代码执行,避免不必要的操作 } catch (Exception $e) { $message1 = "Mail not sent"; echo "<script type='text/javascript'>alert('$message1'); window.location.href='contacto.php';</script>"; exit; }
方式二:通过URL参数传递状态,在目标页显示弹窗
如果需要保留PHP重定向(比如跳转前要处理服务器端逻辑),可以把邮件发送状态通过URL参数传给contacto.php,再在目标页面判断并弹出提示:
1. 修改邮件发送页面的代码
<?php //PHPMailer first part of the code try { //PHPMailer second part of the code $mail->send(); // 传递成功状态参数 header('Location: contacto.php?status=success'); exit; } catch (Exception $e) { // 传递失败状态参数 header('Location: contacto.php?status=fail'); exit; }
2. 在contacto.php中添加弹窗逻辑
在contacto.php的页面头部(比如<body>标签开始处)加入以下代码:
<?php if (isset($_GET['status'])) { $tipMessage = ''; switch ($_GET['status']) { case 'success': $tipMessage = "邮件发送成功"; break; case 'fail': $tipMessage = "邮件发送失败"; break; } echo "<script>alert('{$tipMessage}');</script>"; } ?>
内容的提问来源于stack exchange,提问作者Martín
相关产品推荐
相关产品推荐

