在单页应用中,表单默认提交会触发完整页面刷新或导航,即使已绑定 javascript 处理函数并返回 `false`,仍可能因事件绑定时机或执行顺序问题导致路由变更;正确做法是显式调用 `event.preventdefault()`。
当您为
✅ 正确解决方案是使用标准事件监听器,并在函数首行调用 event.preventDefault():
// 替换原来的:document.querySelector('#compose-form').onsubmit = send_mail; document.querySelector('#compose-form').addEventListener('submit', function(event) {event.preventDefault(); // ✅ 关键:立即阻止默认提交行为 const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; fetch('/emails', { method: 'POST', headers: { 'Content-Type': 'application/json'}, body: JSON.stringify({recipients, subject, body}) }) .then(response => response.json()) .then(result => {console.log('Email sent:', result); load_mailbox('sent'); }) .catch(error => {console.error('Failed to send email:', error); }); });
⚠️ 注意事项:
function send_mail(event) {event.preventDefault(); // ✅ 必须存在 // …… 其余逻辑 } document.querySelector('#compose-form').onsubmit = send_mail;
总结:表单路由跳转的根本原因是 浏览器默认提交行为未被显式阻止。event.preventDefault() 是标准、可靠、语义明确的解决方式,应始终作为表单 AJAX 提交处理函数的第一行代码。
play函数怎么处理网络中断_断线重连机制【教程】
什么是恐惧贪婪指数?如何通过市场情绪指标判断当前的抄底时机?