将库存系统代码从localStorage改为使用服务端JSON文件
库存系统从localStorage切换到服务器JSON文件实现方案
要把依赖localStorage的库存系统改成调用服务器JSON文件存储,且不使用SQL,下面用原生JavaScript的fetch API完成完整替换,步骤如下:
第一步:在服务器上创建JSON文件
在托管服务器根目录下创建inventory.json,初始内容为空数组,用于存储所有库存条目:
[]
第二步:修改JavaScript代码
核心是把所有读写localStorage的操作,替换为对inventory.json的HTTP请求。以下是修改后的完整script.js代码:
document.addEventListener("DOMContentLoaded", () => { const form = document.getElementById("inventoryForm"); const table = document.getElementById("inventoryTable"); let items = []; // 从服务器加载库存数据 async function loadInventory() { try { const response = await fetch('inventory.json'); items = await response.json(); updateInventoryTable(); } catch (error) { console.error('加载库存失败:', error); items = []; } } // 将库存数据保存到服务器 async function saveInventory() { try { await fetch('inventory.json', { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(items), }); } catch (error) { console.error('保存库存失败:', error); } } // 更新并渲染库存表格 function updateInventoryTable() { table.innerHTML = ` <tr> <th>Owner</th> <th>Item Name</th> <th>Quantity</th> <th>Price</th> <th></th> </tr> `; items.forEach((item, index) => { const row = document.createElement("tr"); row.innerHTML = ` <td>${item.owner}</td> <td>${item.name}</td> <td>${item.quantity}</td> <td>${item.price}</td> <td> <button onclick="editItem(${index})">Edit</button> <button onclick="deleteItem(${index})">Delete</button> </td> `; table.appendChild(row); }); } // 添加新库存条目 async function addItem(owner, name, quantity, price) { items.push({owner, name, quantity, price }); await saveInventory(); updateInventoryTable(); } // 删除指定库存条目 async function deleteItem(index) { items.splice(index, 1); await saveInventory(); updateInventoryTable(); } // 表单提交处理逻辑 form.addEventListener("submit", async (e) => { e.preventDefault(); const itemOwner = document.getElementById("itemOwner").value; const itemName = document.getElementById("itemName").value; const itemQuantity = document.getElementById("itemQuantity").value; const itemPrice = document.getElementById("itemPrice").value; await addItem(itemOwner, itemName, itemQuantity, itemPrice); form.reset(); }); // 编辑库存条目 window.editItem = async (index) => { const newOwner = prompt("Enter the new owners name:"); const newName = prompt("Enter the new item name:"); const newQuantity = prompt("Enter the new quantity:"); const newPrice = prompt("Enter the new price:"); if (newOwner && newName && newQuantity && newPrice) { items[index].owner = newOwner; items[index].name = newName; items[index].quantity = newQuantity; items[index].price = newPrice; await saveInventory(); updateInventoryTable(); } }; // 确认删除操作 window.deleteItem = async (index) => { if (confirm("Are you sure you want to delete this item?")) { await deleteItem(index); } }; // 页面加载时初始化库存数据 loadInventory(); });
关键注意事项
- 如果你的静态服务器不支持PUT请求修改文件,需要添加简单后端接口处理JSON读写。示例Node.js+Express后端代码(可选):
// server.js const express = require('express'); const fs = require('fs'); const app = express(); const port = 3000; app.use(express.json()); // 获取库存数据 app.get('/inventory.json', (req, res) => { fs.readFile('inventory.json', 'utf8', (err, data) => { if (err) { res.status(500).json([]); return; } res.json(JSON.parse(data)); }); }); // 保存库存数据 app.put('/inventory.json', (req, res) => { fs.writeFile('inventory.json', JSON.stringify(req.body), 'utf8', (err) => { if (err) { res.status(500).send('保存失败'); return; } res.send('保存成功'); }); }); app.use(express.static('public')); // 指定静态文件目录 app.listen(port, () => { console.log(`服务器运行在 http://localhost:${port}`); });
- 确保服务器上的
inventory.json文件具备写入权限,否则保存操作会失败。 - 所有修改数据的操作都改为异步函数,因为
fetch是异步操作,需用await等待执行完成。
内容的提问来源于stack exchange,提问作者Beejster
相关产品推荐
相关产品推荐

