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 的基础 URL
        const 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 显示内容

效果如下:

posted @ 2025-11-07 08:44  冀未然  阅读(5)  评论(0)    收藏  举报