首先,需要确保Ajax中的数据在发送到php之前已经正确地收集和处理,可以通过console.log()在浏览器控制台中输出结果来检查。 然后,在php脚本中,应该使用$_POST变量来获取通过Ajax发送的数据。最后,使用相应的PHP邮件发送库将数据添加到邮件中并发送。
以下是具体代码示例:
Ajax代码:
$.ajax({ url: 'send_mail.php', type: 'POST', data: { name: $('#name').val(), email: $('#email').val(), message: $('#message').val() }, success: function(response) { console.log(response); alert('邮件已发送'); }, error: function(error) { console.log(error); alert('发送邮件失败,请检查您的网络连接和配置设置。'); } });
PHP代码:
require_once "phpmailer/class.phpmailer.php";// 引用邮件发送库
$mail = new PHPMailer(); // 实例化邮件发送对象 $mail->IsSMTP(); // 配置SMTP服务器信息
$mail->From = $email; $mail->AddAddress('receiver@domain.com'); $mail->Subject = '来自'.$name.'的邮件'; $mail->Body = $message;
if(!$mail->Send()) { echo '邮件发送失败,请重试或联系网站管理员。'; } else { echo '邮件已成功发送'; } ?>