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

编程新手求助:如何将网站联系表单数据保存至json-server

解决方法:将表单数据提交到json-server

嘿,Ana!别担心,这事儿挺容易搞定的,咱们一步步来,把你的表单和json-server连起来,让每一条表单数据都能存进去:

第一步:调整你的HTML结构

首先,咱们得把输入框和提交按钮放进一个<form>标签里,这样能更规范地监听提交事件(当然也可以直接监听按钮点击,但用form更符合表单语义化)。修改后的HTML大概是这样:

<section class="enquiries">
  <form id="contactForm">
    <input type="text" name="name" id="name" autofocus placeholder=" Name:" required>
    <br>
    <input type="email" name="email" id="email" placeholder=" Email:" required>
    <br>
    <input type="text" name="subject" id="subject" placeholder=" Subject:" required>
    <br>
    <textarea id="extra" name="extra" placeholder=" Message..." required></textarea>
    <br>
    <button class="button" type="submit">Send</button>
  </form>
</section>

我加了required属性确保用户填完必填项,也把多余的</input>标签去掉了(input是自闭合标签,不需要手动闭合)。

第二步:写JavaScript提交逻辑

接下来咱们写JS代码,监听表单的提交事件,收集输入数据,然后用fetch API发送POST请求到json-server:

// 获取表单元素
const contactForm = document.getElementById('contactForm');

// 监听表单提交事件
contactForm.addEventListener('submit', async (e) => {
  // 阻止表单默认的刷新页面行为
  e.preventDefault();

  // 收集表单里的所有输入值
  const formData = {
    name: document.getElementById('name').value,
    email: document.getElementById('email').value,
    subject: document.getElementById('subject').value,
    extra: document.getElementById('extra').value
  };

  try {
    // 发送POST请求到json-server的contactInfo端点
    const response = await fetch('http://localhost:3000/contactInfo', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData)
    });

    // 验证请求是否成功
    if (response.ok) {
      alert('消息提交成功!');
      // 清空表单
      contactForm.reset();
    } else {
      throw new Error('提交失败,请重试');
    }
  } catch (error) {
    alert(`出错了:${error.message}`);
  }
});

几个关键说明:

  • async/await是让异步代码看起来更像同步代码,你也可以用.then()的写法,不过前者更直观。
  • json-server默认运行在http://localhost:3000,如果你的端口不一样,记得改成自己的端口。
  • 不用手动设置id字段,json-server会自动给每条新增的数据生成唯一的id。

第三步:准备好json-server

先把你的db.json里那条空数据删掉,改成更干净的初始结构:

{
  "contactInfo": []
}

然后启动json-server:

json-server --watch db.json

启动后你可以访问http://localhost:3000/contactInfo查看所有提交的数据。

测试一下

现在打开你的网页,填好表单点击Send,然后去看db.json或者访问上面的URL,就能看到新提交的数据已经存进去啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:03:34