JSON-server 数据操作示例

JSON-server 数据操作示例

使用 JavaScript Fetch API 对 JSON-server 进行 CRUD 操作

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>JSON-server 数据操作示例</title><style>* {box-sizing: border-box;margin: 0;padding: 0;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}body {background-color: #f5f7fa;color: #333;line-height: 1.6;padding: 20px;}.container {max-width: 1200px;margin: 0 auto;padding: 20px;}header {text-align: center;margin-bottom: 30px;padding: 20px;background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);color: white;border-radius: 10px;box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);}h1 {font-size: 2.5rem;margin-bottom: 10px;}.description {font-size: 1.1rem;opacity: 0.9;}.main-content {display: grid;grid-template-columns: 1fr 2fr;gap: 30px;}@media (max-width: 768px) {.main-content {grid-template-columns: 1fr;}}.form-section {background: white;padding: 25px;border-radius: 10px;box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);}.data-section {background: white;padding: 25px;border-radius: 10px;box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);}h2 {color: #2c3e50;margin-bottom: 20px;padding-bottom: 10px;border-bottom: 2px solid #f0f0f0;}.form-group {margin-bottom: 20px;}label {display: block;margin-bottom: 8px;font-weight: 600;color: #34495e;}input, textarea {width: 100%;padding: 12px;border: 1px solid #ddd;border-radius: 6px;font-size: 16px;transition: border 0.3s;}input:focus, textarea:focus {border-color: #3498db;outline: none;box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);}.btn-group {display: flex;gap: 10px;flex-wrap: wrap;}button {padding: 12px 20px;border: none;border-radius: 6px;cursor: pointer;font-size: 16px;font-weight: 600;transition: all 0.3s;}.btn-primary {background-color: #3498db;color: white;}.btn-primary:hover {background-color: #2980b9;}.btn-success {background-color: #2ecc71;color: white;}.btn-success:hover {background-color: #27ae60;}.btn-warning {background-color: #f39c12;color: white;}.btn-warning:hover {background-color: #d35400;}.btn-danger {background-color: #e74c3c;color: white;}.btn-danger:hover {background-color: #c0392b;}.btn-secondary {background-color: #95a5a6;color: white;}.btn-secondary:hover {background-color: #7f8c8d;}table {width: 100%;border-collapse: collapse;margin-top: 20px;}th, td {padding: 12px 15px;text-align: left;border-bottom: 1px solid #e0e0e0;}th {background-color: #f8f9fa;font-weight: 600;color: #2c3e50;}tr:hover {background-color: #f8f9fa;}.actions {display: flex;gap: 8px;}.message {padding: 15px;border-radius: 6px;margin-bottom: 20px;display: none;}.success {background-color: #d4edda;color: #155724;border: 1px solid #c3e6cb;}.error {background-color: #f8d7da;color: #721c24;border: 1px solid #f5c6cb;}.loading {text-align: center;padding: 20px;display: none;}.spinner {border: 4px solid rgba(0, 0, 0, 0.1);border-left-color: #3498db;border-radius: 50%;width: 40px;height: 40px;animation: spin 1s linear infinite;margin: 0 auto 15px;}@keyframes spin {to { transform: rotate(360deg); }}footer {text-align: center;margin-top: 40px;padding: 20px;color: #7f8c8d;font-size: 0.9rem;}</style>
</head>
<body><div class="container"><header><h1>JSON-server 数据操作示例</h1><p class="description">使用 JavaScript Fetch API 对 JSON-server 进行 CRUD 操作</p></header><div class="message" id="message"></div><div class="main-content"><section class="form-section"><h2>用户表单</h2><form id="userForm"><div class="form-group"><label for="userId">用户 ID (仅用于更新和删除)</label><input type="text" id="userId" placeholder="留空以创建新用户"></div><div class="form-group"><label for="name">姓名</label><input type="text" id="name" required></div><div class="form-group"><label for="email">邮箱</label><input type="email" id="email" required></div><div class="form-group"><label for="phone">电话</label><input type="text" id="phone"></div><div class="form-group"><label for="address">地址</label><textarea id="address" rows="3"></textarea></div><div class="btn-group"><button type="submit" class="btn-primary">创建用户</button><button type="button" id="updateBtn" class="btn-success">更新用户</button><button type="button" id="deleteBtn" class="btn-danger">删除用户</button><button type="button" id="clearBtn" class="btn-secondary">清空表单</button></div></form></section><section class="data-section"><h2>用户数据</h2><div class="btn-group"><button id="getAllBtn" class="btn-primary">获取所有用户</button><button id="getByIdBtn" class="btn-success">根据ID获取用户</button></div><div class="loading" id="loading"><div class="spinner"></div><p>加载中...</p></div><table id="usersTable"><thead><tr><th>ID</th><th>姓名</th><th>邮箱</th><th>电话</th><th>操作</th></tr></thead><tbody id="usersTableBody"><!-- 用户数据将在这里动态生成 --></tbody></table></section></div><footer><p>注意:请确保 JSON-server 正在运行在 http://localhost:3000</p><p>启动命令: json-server --watch db.json --port 3000</p></footer></div><script>// JSON-server 的基础 URLconst API_BASE_URL = 'http://localhost:3000';// DOM 元素const userForm = document.getElementById('userForm');const userIdInput = document.getElementById('userId');const nameInput = document.getElementById('name');const emailInput = document.getElementById('email');const phoneInput = document.getElementById('phone');const addressInput = document.getElementById('address');const updateBtn = document.getElementById('updateBtn');const deleteBtn = document.getElementById('deleteBtn');const clearBtn = document.getElementById('clearBtn');const getAllBtn = document.getElementById('getAllBtn');const getByIdBtn = document.getElementById('getByIdBtn');const usersTableBody = document.getElementById('usersTableBody');const messageDiv = document.getElementById('message');const loadingDiv = document.getElementById('loading');// 显示消息function showMessage(message, type = 'success') {messageDiv.textContent = message;messageDiv.className = `message ${type}`;messageDiv.style.display = 'block';// 3秒后自动隐藏消息setTimeout(() => {messageDiv.style.display = 'none';}, 3000);}// 显示/隐藏加载指示器function setLoading(loading) {loadingDiv.style.display = loading ? 'block' : 'none';}// 获取所有用户async function getAllUsers() {setLoading(true);try {const response = await fetch(`${API_BASE_URL}/users`);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const users = await response.json();displayUsers(users);showMessage(`成功获取 ${users.length} 个用户`);} catch (error) {console.error('获取用户时出错:', error);showMessage(`获取用户失败: ${error.message}`, 'error');} finally {setLoading(false);}}// 根据ID获取用户async function getUserById() {const id = userIdInput.value.trim();if (!id) {showMessage('请输入用户ID', 'error');return;}setLoading(true);try {const response = await fetch(`${API_BASE_URL}/users/${id}`);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const user = await response.json();displayUsers([user]);showMessage(`成功获取用户 ID: ${id}`);} catch (error) {console.error('获取用户时出错:', error);showMessage(`获取用户失败: ${error.message}`, 'error');} finally {setLoading(false);}}// 创建用户async function createUser(userData) {setLoading(true);try {const response = await fetch(`${API_BASE_URL}/users`, {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify(userData),});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const newUser = await response.json();showMessage(`用户创建成功,ID: ${newUser.id}`);clearForm();getAllUsers(); // 刷新用户列表} catch (error) {console.error('创建用户时出错:', error);showMessage(`创建用户失败: ${error.message}`, 'error');} finally {setLoading(false);}}// 更新用户async function updateUser(id, userData) {setLoading(true);try {const response = await fetch(`${API_BASE_URL}/users/${id}`, {method: 'PUT',headers: {'Content-Type': 'application/json',},body: JSON.stringify(userData),});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const updatedUser = await response.json();showMessage(`用户更新成功,ID: ${updatedUser.id}`);clearForm();getAllUsers(); // 刷新用户列表} catch (error) {console.error('更新用户时出错:', error);showMessage(`更新用户失败: ${error.message}`, 'error');} finally {setLoading(false);}}// 删除用户async function deleteUser(id) {if (!confirm(`确定要删除用户 ID: ${id} 吗?`)) {return;}setLoading(true);try {const response = await fetch(`${API_BASE_URL}/users/${id}`, {method: 'DELETE',});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}showMessage(`用户删除成功,ID: ${id}`);clearForm();getAllUsers(); // 刷新用户列表} catch (error) {console.error('删除用户时出错:', error);showMessage(`删除用户失败: ${error.message}`, 'error');} finally {setLoading(false);}}// 在表格中显示用户function displayUsers(users) {usersTableBody.innerHTML = '';if (users.length === 0) {usersTableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">没有找到用户数据</td></tr>';return;}users.forEach(user => {const row = document.createElement('tr');row.innerHTML = `<td>${user.id}</td><td>${user.name || ''}</td><td>${user.email || ''}</td><td>${user.phone || ''}</td><td class="actions"><button class="btn-warning" onclick="fillFormForEdit(${user.id})">编辑</button><button class="btn-danger" onclick="deleteUser(${user.id})">删除</button></td>`;usersTableBody.appendChild(row);});}// 填充表单以编辑用户async function fillFormForEdit(id) {setLoading(true);try {const response = await fetch(`${API_BASE_URL}/users/${id}`);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const user = await response.json();userIdInput.value = user.id;nameInput.value = user.name || '';emailInput.value = user.email || '';phoneInput.value = user.phone || '';addressInput.value = user.address || '';showMessage(`已加载用户 ID: ${id} 的数据`);} catch (error) {console.error('获取用户数据时出错:', error);showMessage(`获取用户数据失败: ${error.message}`, 'error');} finally {setLoading(false);}}// 清空表单function clearForm() {userForm.reset();}// 事件监听器userForm.addEventListener('submit', function(e) {e.preventDefault();const userData = {name: nameInput.value,email: emailInput.value,phone: phoneInput.value,address: addressInput.value,};createUser(userData);});updateBtn.addEventListener('click', function() {const id = userIdInput.value.trim();if (!id) {showMessage('请输入用户ID', 'error');return;}const userData = {name: nameInput.value,email: emailInput.value,phone: phoneInput.value,address: addressInput.value,};updateUser(id, userData);});deleteBtn.addEventListener('click', function() {const id = userIdInput.value.trim();if (!id) {showMessage('请输入用户ID', 'error');return;}deleteUser(id);});clearBtn.addEventListener('click', clearForm);getAllBtn.addEventListener('click', getAllUsers);getByIdBtn.addEventListener('click', getUserById);// 页面加载时获取所有用户document.addEventListener('DOMContentLoaded', getAllUsers);</script>
</body>
</html>

users.json 如下:

{"users": [{"id": "1","name": "张三","email": "zhangsan@example.com","phone": "13800138000","address": "北京市朝阳区"},{"name": "李四2","email": "lisi@example.com","phone": "13900139000","address": "上海市浦东新区","id": "2"}]
}

步骤如下:

1、安装node.js

2、执行nmp install json-server

3、执行json-server 目录\users.json

会出现提示可执行: http://localhost:3000/users 显示内容

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/958362.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2025年口碑好的针织网眼布最新TOP品牌厂家排行

2025年口碑好的针织网眼布最新TOP品牌厂家排行 针织网眼布因其透气性、弹性、耐用性等特性,在鞋材、服装、家纺、箱包等领域广泛应用。随着市场需求的增长,越来越多的企业专注于高品质网眼布的研发与生产。2025年,…

Python四大容器核心操作速查表(全面版)

Python四大容器核心操作速查表(全面版) 说明时间复杂度标注:O(1)=常数级(快),O(n)=线性级(随数据量增长),O(k)=取决于传入可迭代对象长度 🔴 不可变容器(元组)的增删改操作均为“间接实现”,直接操作会报…

2025年热门的工业盐烘干机品牌厂家排行榜

2025年热门的工业盐烘干机品牌厂家排行榜 工业盐烘干机是化工、食品、医药等行业中不可或缺的设备,其性能直接影响生产效率和产品质量。随着技术进步和环保要求的提高,高效节能、智能化的烘干设备成为市场主流。以下…

2025年优质的高阻隔贴体膜厂家最新TOP排行榜

2025年优质的高阻隔贴体膜厂家最新TOP排行榜 随着食品保鲜、医疗包装、工业防护等领域对高阻隔材料需求的快速增长,贴体膜作为包装行业的关键材料,其性能与品质直接影响产品的保质期和安全性。2025年,高阻隔贴体膜…

2025 年通风气楼源头厂家最新推荐排行榜:聚焦专业制造标杆企业,精选优质品牌助力选购中脊通风气楼/工业厂房通风气楼公司推荐

引言 近期,行业权威协会针对通风气楼领域开展专项测评,通过多维度严苛考核,发布了 2025 年通风气楼源头厂家最新推荐榜单。此次测评采用科学系统的方法,从技术实力、产品质量、服务水平、市场口碑四大核心维度入手…

2025年口碑好的防雷汇流箱品牌厂家排行榜

2025年口碑好的防雷汇流箱品牌厂家排行榜 随着光伏发电行业的快速发展,防雷汇流箱作为光伏发电系统中的关键设备,其性能和可靠性直接影响整个系统的安全与效率。2025年,市场上涌现出一批技术领先、质量可靠的防雷汇…

CF2164E 小结

这题就是昨天晚上 Golble Round 的 E,感觉这题还可以。 就是首先要观察到这个图的状态有可能不是一个欧拉图。所以你需要通过第二种操作来建一些虚边。然后对于每对虚点,计算答案。 首先这个考虑虚点的顺序和排列方式…

2025 密封胶条厂家最新推荐榜:高校合作 + 全流程质控,权威测评靠谱品牌盘点门窗密封胶条/三元乙丙密封胶条/汽车密封胶条公司推荐

引言 密封胶条作为多行业核心配套产品,其质量直接影响下游产品性能与安全,但市场仍存在原料劣质、性能不达标、服务滞后等问题。为精准指引采购决策,行业协会联合检测机构开展 2025 年度测评,涵盖 120 余家企业。测…

2025年比较好的新能源汽车直流接触器厂家最新权威实力榜

2025年比较好的新能源汽车直流接触器厂家最新权威实力榜随着新能源汽车行业的蓬勃发展,直流接触器作为电动汽车高压系统的关键部件,其市场需求呈现爆发式增长。直流接触器承担着电池系统与整车电路之间的连接与断开功…

2025年上海血管瘤医院联系电话推荐:瑞椿领衔权威榜单

在血管瘤这一特殊疾病面前,患者与家属最迫切的需求往往是“找到真正专业、随时能联系上的医院”。上海作为医疗资源高度集中的城市,机构众多,广告信息混杂,如何快速锁定口碑扎实、技术领先、电话畅通的医疗机构,成…

2025年热门的网架加工厂家推荐及采购参考

2025年热门的网架加工厂家推荐及采购参考 随着建筑行业的快速发展,网架结构因其轻量化、高强度、施工便捷等优势,广泛应用于体育场馆、工业厂房、机场航站楼等领域。选择一家技术实力强、口碑优良的网架加工厂家至关…

2025年评价高的煤矿道岔厂家最新推荐排行榜

2025年评价高的煤矿道岔厂家最新推荐排行榜 煤矿道岔作为矿山运输系统的关键设备,其质量与性能直接影响煤矿生产的安全性和效率。随着技术的不断进步,市场对道岔产品的精度、耐用性和智能化要求越来越高。2025年,经…

2025年上海血管瘤医院联系电话推荐:瑞椿领航五强精选

在上海这样一座医疗资源高度集中的城市,血管瘤虽属良性病变,却因常出现在新生儿及颜面、关节等关键部位,让家庭格外焦虑。家长与成年患者最关心的问题无外乎:哪家医院经验多、设备新、预约快、后续随访方便?2025年…

2025年靠谱的暗扣隐藏式家具拉手厂家最新TOP排行榜

2025年靠谱的暗扣隐藏式家具拉手厂家最新TOP排行榜 在现代家居设计中,暗扣隐藏式拉手凭借其简约美观、安全实用的特性,逐渐成为高端定制家具的首选配件。这类拉手不仅能提升家具的整体质感,还能避免凸起设计带来的…

2025年上海血管瘤医院联系电话推荐:微创激光全程指引

在上海这样医疗资源高度集中的城市,血管瘤患者及家属最迫切的需求是“第一时间找到靠谱医院并顺利联系”。血管瘤虽多为良性,却可能因生长部位特殊或体积迅速增大而影响功能、外观,甚至危及生命,早诊断、早干预尤为…

2025 年上海中医诊所口碑排行榜最新发布,经方治疗 + 道地药材加持,上海中医调理/上海民间中医/江浙沪经方中医/上海传统中医诊所推荐

引言 当前中医诊疗行业中,部分机构存在看诊时间短、药材质量把控不严、疑难病症诊疗能力不足、诊疗系统落后等问题,给患者就诊带来困扰。为筛选优质中医诊所,本次榜单由行业权威协会主导测评,结合多维度数据生成。…

2025年比较好的回转式格栅机厂家最新用户好评榜

2025年比较好的回转式格栅机厂家最新用户好评榜回转式格栅机是污水处理、工业废水处理等领域的关键设备,其性能直接影响整个水处理系统的效率。随着环保要求的不断提高,市场对高质量、高可靠性的回转式格栅机需求持续…

2025年知名的伴热带厂家最新推荐排行榜

2025年知名的伴热带厂家最新推荐排行榜 伴热带作为一种高效、安全、节能的电加热产品,广泛应用于石油化工、建筑、电力、食品医药等多个行业。随着技术的不断进步和市场需求的增长,伴热带厂家之间的竞争也日趋激烈。…

LiveLessons - Introduction to the FreeBSD Open-Source Operating System

Description This ten-hour video starts with an introduction to the FreeBSD community and explains how it differs from the Linux ecosystem. The video then goes on to provide a firm background in the Fre…

2025年靠谱的矿石吨袋厂家最新TOP排行榜

2025年靠谱的矿石吨袋厂家最新TOP排行榜 在矿石、化工、建材等重工业领域,吨袋(集装袋)作为大宗物料的运输包装核心工具,其质量直接影响运输安全和成本控制。2025年,随着行业对高强度、耐磨损、环保性要求的提升…