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

使用json-server+fetch提交数据,调用e.preventDefault仍页面刷新求助

解决form提交后页面自动刷新的问题

你的代码逻辑本身是正确的,但页面仍刷新大概率是事件监听器没有成功绑定到form元素导致的,以下是具体排查和解决步骤:

1. 确保JS代码在DOM加载完成后执行

如果你的JavaScript代码写在<head>标签里,或者页面元素还没渲染就执行了JS,document.querySelector("form")会返回null,事件绑定失败,自然e.preventDefault()不会生效。

解决方法:

  • 把JS代码移到<body>标签的最末尾,确保form元素已经渲染完成:
<body>
  <form>
    <input type="text" name="firstName" placeholder="first name" />
    <input type="text" name="lastName" placeholder="last name" />
    <button type="submit">send user</button>
  </form>
  <!-- JS放在这里 -->
  <script>
    const postForm = document.querySelector("form");
    postForm.addEventListener("submit", async (e) => {
      e.preventDefault();
      const firstName = postForm.firstName.value;
      const lastName = postForm.lastName.value;

      await fetch("http://localhost:3000/users", {
        method: "POST",
        body: JSON.stringify({ firstName, lastName }),
        headers: { "Content-Type": "application/json" },
      });
    });
  </script>
</body>
  • 或者用DOMContentLoaded事件包裹代码,确保DOM加载完成后再执行:
document.addEventListener('DOMContentLoaded', () => {
  const postForm = document.querySelector("form");
  postForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    const firstName = postForm.firstName.value;
    const lastName = postForm.lastName.value;

    await fetch("http://localhost:3000/users", {
      method: "POST",
      body: JSON.stringify({ firstName, lastName }),
      headers: { "Content-Type": "application/json" },
    });
  });
});

2. 检查是否存在其他冲突的事件监听器

如果页面上还有其他JavaScript代码监听了该form的submit事件,且没有正确阻止默认行为,也可能导致页面刷新。可以在浏览器开发者工具的Elements -> Event Listeners里查看form元素的所有submit事件,移除或修改冲突的监听器。

3. 添加错误处理避免潜在问题

虽然e.preventDefault()在最前面执行,但如果fetch请求抛出未捕获的错误,可能导致后续代码异常(不过不会直接引发刷新),建议加上try/catch做错误处理,同时可以在请求成功后清空表单提升体验:

postForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  try {
    const firstName = postForm.firstName.value;
    const lastName = postForm.lastName.value;
    const response = await fetch("http://localhost:3000/users", {
      method: "POST",
      body: JSON.stringify({ firstName, lastName }),
      headers: { "Content-Type": "application/json" },
    });
    if (!response.ok) throw new Error(`请求失败:${response.status}`);
    // 请求成功后清空表单
    postForm.reset();
  } catch (err) {
    console.error("提交失败:", err);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:50:23