如何用HTML/CSS/JS获取表单数据存入表格并实现多用户持久化存储
你判断的没错,要实现多用户可见、刷新永久保留数据的需求,必须搭配服务端和数据库实现,纯前端本地存储只能满足当前设备当前浏览器的临时存储需求。以下是完整可运行的实现方案:
1 调整前端代码
你原本的代码缺少提交按钮、表格结构,也没有和后端交互的逻辑,修改后的完整前端代码如下:
<!DOCTYPE html> <html> <head> <title>姓名收集表</title> </head> <body> <!-- 表单部分 --> <form id="nameForm"> <label for="name">Name:</label><br> <input type="text" id="name" name="name" required><br><br> <button type="submit">创建</button> </form> <br> <!-- 表格部分 --> <table id="infotable" border="1"> <tr> <th>姓名</th> </tr> </table> <script> const table = document.getElementById("infotable"); const form = document.getElementById("nameForm"); // 页面加载时拉取所有已存的姓名 async function loadAllNames() { const res = await fetch("http://localhost:3000/get-names"); const names = await res.json(); // 清空原有除表头外的行 while(table.rows.length > 1) { table.deleteRow(1); } // 渲染所有姓名 names.forEach(name => { const row = table.insertRow(-1); const cell = row.insertCell(0); cell.innerText = name; }) } // 表单提交逻辑 form.addEventListener("submit", async (e) => { e.preventDefault(); const name = document.getElementById("name").value.trim(); if(!name) return; // 提交给后端 await fetch("http://localhost:3000/add-name", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({name: name}) }) // 重新拉取数据刷新表格 await loadAllNames(); // 清空输入框 form.reset(); }) // 页面加载完成后自动拉取数据 window.onload = loadAllNames; </script> </body> </html>
把以上代码保存为index.html文件。
2 编写轻量化后端服务
我们用新手最容易上手的Node.js实现后端,全程不需要复杂配置:
- 先下载安装Node.js(安装完成后打开终端输入
node -v能输出版本号就说明安装成功) - 新建一个空文件夹作为后端项目,在文件夹内打开终端,依次执行以下命令初始化项目:
npm init -y npm install express sqlite3 cors
- 在文件夹内新建
server.js文件,写入以下代码:
const express = require('express'); const sqlite3 = require('sqlite3').verbose(); const cors = require('cors'); const app = express(); const port = 3000; // 允许跨域请求 app.use(cors()); app.use(express.json()); // 连接SQLite数据库,没有会自动创建数据库文件 const db = new sqlite3.Database('./names.db', (err) => { if (err) console.error(err.message); // 创建存储姓名的表,不存在就自动创建 db.run(`CREATE TABLE IF NOT EXISTS names ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL )`); }); // 提交姓名的接口 app.post('/add-name', (req, res) => { const {name} = req.body; db.run(`INSERT INTO names (name) VALUES (?)`, [name], function(err) { if (err) return res.status(500).json({error: err.message}); res.json({success: true, id: this.lastID}); }); }); // 获取所有姓名的接口 app.get('/get-names', (req, res) => { db.all(`SELECT name FROM names`, [], (err, rows) => { if (err) return res.status(500).json({error: err.message}); const names = rows.map(row => row.name); res.json(names); }); }); app.listen(port, () => { console.log(`服务运行在 http://localhost:${port}`); });
3 启动项目验证效果
- 在后端项目文件夹终端执行
node server.js启动后端服务 - 直接双击打开之前保存的
index.html文件,就可以正常使用了 - 验证效果:输入姓名点击提交会自动新增行,刷新页面数据不会丢失,同局域网下其他设备访问你电脑的IP+3000端口也能看到所有已提交的姓名。如果要让所有公网用户都能访问,把这套服务部署到公网服务器即可,核心逻辑不用修改。
内容的提问来源于stack exchange,提问作者Pratyush
相关产品推荐
相关产品推荐

