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

使用EmailJS的联系表单提交后清空且发送空数据问题求助

联系表单提交后清空但无法发送有效数据的问题解决

问题根源

  1. JS代码执行时机错误:你当前的JS代码在页面加载完成后立即执行,此时所有输入框都是空值,因此params对象存储的全是空内容,后续点击提交时发送的始终是这个空参数。
  2. 函数定义不完整:你的JS代码没有正确包裹在sendMail()函数中,导致点击按钮调用该函数时,无法执行预期的表单数据获取与发送逻辑。
  3. 未阻止表单默认提交行为:点击type="submit"的按钮会触发表单默认提交动作(页面刷新),这就是表单清空的直接原因,同时页面刷新会中断JS的邮件发送流程。

修复步骤

1. 修正JS代码,确保点击时获取实时输入值

将JS代码改为以下结构,保证在提交时才读取当前输入框的内容:

function sendMail(e) {
  // 阻止表单默认刷新行为
  e.preventDefault();
  
  // 提交时实时获取输入框值
  var params = {
    name: document.getElementById("name").value,
    phone: document.getElementById("phone").value,
    email: document.getElementById("email").value,
    message: document.getElementById("message").value,
  };

  emailjs.send("service_xnukp8n", "template_mv0tglo", params)
    .then(function(res) {
      alert("Your form was sent successfully! " + res.status);
      // 发送成功后手动清空表单
      document.querySelector("form").reset();
    })
    .catch((err) => console.log(err));
}

2. 修改HTML按钮,传递事件参数

把按钮的onclick属性改为传递事件对象,让JS可以阻止默认行为:

<button class="btn btn-primary" type="submit" onclick="sendMail(event)">Submit <i class="fas fa-paper-plane"></i></button>

更规范的替代方案:给表单绑定submit事件

去掉按钮的onclick,给表单添加ID后通过JS监听提交事件:

<form id="contact-form">
  <!-- 原有表单内容保持不变 -->
  <button class="btn btn-primary" type="submit">Submit <i class="fas fa-paper-plane"></i></button>
</form>

对应的JS代码:

document.getElementById("contact-form").addEventListener("submit", function(e) {
  e.preventDefault();
  
  var params = {
    name: document.getElementById("name").value,
    phone: document.getElementById("phone").value,
    email: document.getElementById("email").value,
    message: document.getElementById("message").value,
  };

  emailjs.send("service_xnukp8n", "template_mv0tglo", params)
    .then(function(res) {
      alert("Your form was sent successfully! " + res.status);
      document.getElementById("contact-form").reset();
    })
    .catch((err) => console.log(err));
});

额外检查点

  • 确认EmailJS的service ID和template ID配置正确,且账户已完成对应服务与模板的设置。
  • 确保页面已正确引入EmailJS SDK,并完成初始化(比如添加<script src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js"></script>,并调用emailjs.init("你的用户ID"))。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:55:21