使用EmailJS的联系表单提交后清空且发送空数据问题求助
联系表单提交后清空但无法发送有效数据的问题解决
问题根源
- JS代码执行时机错误:你当前的JS代码在页面加载完成后立即执行,此时所有输入框都是空值,因此
params对象存储的全是空内容,后续点击提交时发送的始终是这个空参数。 - 函数定义不完整:你的JS代码没有正确包裹在
sendMail()函数中,导致点击按钮调用该函数时,无法执行预期的表单数据获取与发送逻辑。 - 未阻止表单默认提交行为:点击
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
相关产品推荐
相关产品推荐

