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

表单提交数据持久化问题求助:页面刷新后数据丢失

表单数据持久化存储问题

我在理解HTML表单时遇到困难:将表单提交的数据存入数组后,页面刷新时数组中的提交数据便会丢失。我还尝试通过POST方法向JSON文件写入数据,但同样无法成功存储表单数据。

附上相关代码如下:

存入数组的代码

const inputs = document.getElementsByClassName("inputs");
const form = document.querySelector("#form-user");

const [nameText, age, carBrand, textArea] = inputs;

const data = []

form.addEventListener("submit", (event) => {
    event.preventDefault();
    data.push({
        name: nameText.value,
        age: age.value,
        carBrand: carBrand.value,
        textArea: textArea.value
    })
})

尝试写入JSON文件的代码

form.addEventListener("submit", (event) => {
  event.preventDefault();
  fetch("../data/data.json", {
    method: "POST",
    body: JSON.stringify({
      name: nameText.value,
      age: age.value,
      carBrand: carBrand.value,
      textArea: textArea.value
    })
  })

解决方案1:前端本地存储(无需后端)

浏览器自带localStorage和sessionStorageAPI,能把数据存在用户本地浏览器中,页面刷新后数据不会丢失。其中:

  • localStorage:数据永久保存,除非用户手动清除浏览器缓存
  • sessionStorage:仅在当前浏览器会话有效,关闭浏览器后数据清空

修改存入数组的代码,整合本地存储:

const inputs = document.getElementsByClassName("inputs");
const form = document.querySelector("#form-user");

const [nameText, age, carBrand, textArea] = inputs;

// 页面加载时,从localStorage读取已保存的数据,没有则初始化空数组
let data = JSON.parse(localStorage.getItem('formData')) || [];

form.addEventListener("submit", (event) => {
    event.preventDefault();
    const newDataItem = {
        name: nameText.value,
        age: age.value,
        carBrand: carBrand.value,
        textArea: textArea.value
    };
    data.push(newDataItem);
    // 将更新后的数组转成JSON字符串,存回localStorage
    localStorage.setItem('formData', JSON.stringify(data));
    // 可选:提交后清空表单
    form.reset();
})

如果需要在页面加载后展示已保存的数据,可以添加渲染逻辑:

// 渲染已保存的数据到页面
function renderSavedData() {
    const dataContainer = document.getElementById('data-container');
    if (!dataContainer) return;
    
    data.forEach(item => {
        const itemElement = document.createElement('div');
        itemElement.innerHTML = `
            <p><strong>姓名:</strong> ${item.name}</p>
            <p><strong>年龄:</strong> ${item.age}</p>
            <p><strong>汽车品牌:</strong> ${item.carBrand}</p>
            <p><strong>备注:</strong> ${item.textArea}</p>
            <hr>
        `;
        dataContainer.appendChild(itemElement);
    });
}

// 页面加载完成后执行渲染
window.addEventListener('load', renderSavedData);

解决方案2:后端接口存储(永久跨设备保存)

直接用POST请求本地JSON文件是无效的——浏览器没有权限修改服务器上的文件。必须通过后端服务接收请求,再将数据写入文件或数据库。

以下是Node.js + Express的极简示例:

  1. 初始化项目并安装依赖:
mkdir form-server && cd form-server
npm init -y
npm install express body-parser
  1. 编写后端代码(server.js):
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');

const app = express();
// 解析JSON格式的请求体
app.use(bodyParser.json());
// 托管前端静态文件(把前端HTML/CSS/JS放在public文件夹)
app.use(express.static('public'));

// 处理表单提交的POST接口
app.post('/api/save-form', (req, res) => {
    const dataFile = path.join(__dirname, 'data', 'data.json');
    // 确保data文件夹存在
    if (!fs.existsSync(path.dirname(dataFile))) {
        fs.mkdirSync(path.dirname(dataFile));
    }
    // 读取现有数据
    let savedData = [];
    if (fs.existsSync(dataFile)) {
        savedData = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
    }
    // 添加新数据并写入文件
    savedData.push(req.body);
    fs.writeFileSync(dataFile, JSON.stringify(savedData, null, 2));
    // 返回成功响应
    res.status(200).json({ status: 'success', message: '数据已保存' });
});

// 启动服务器
app.listen(3000, () => {
    console.log('服务器运行在 http://localhost:3000');
});
  1. 修改前端fetch代码,请求后端接口:
form.addEventListener("submit", (event) => {
  event.preventDefault();
  fetch("/api/save-form", {
    method: "POST",
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: nameText.value,
      age: age.value,
      carBrand: carBrand.value,
      textArea: textArea.value
    })
  })
  .then(response => response.json())
  .then(result => {
      console.log(result.message);
      form.reset();
  })
  .catch(error => {
      console.error('保存失败:', error);
  });
})

运行node server.js启动后端,访问http://localhost:3000即可测试表单提交,数据会被写入data/data.json文件中。


内容的提问来源于stack exchange,提问作者André Silveira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:06