使用 AJAX+JSON 实现用户查询/添加功能
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简单的示例,展示了如何使用AJAX和JSON来实现用户查询和添加的功能。这里假设我们有一个简单的后端API,它可以处理用户的查询请求和添加请求。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Management</title>
    <script>
        function fetchUsers() {
            // 发送GET请求到/api/users获取用户列表
            fetch('/api/users')
                .then(response => response.json())
                .then(data => {
                    // 使用JSON数据更新页面的用户列表
                    const userList = document.getElementById('user-list');
                    userList.innerHTML = ''; // 清空之前的用户列表
                    data.forEach(user => {
                        const li = document.createElement('li');
                        li.textContent = user.name;
                        userList.appendChild(li);
                    });
                })
                .catch(error => console.error('Unable to get users.', error));
        }
 
        function addUser(name) {
            // 构建要发送的数据对象
            const user = { name };
            // 将对象转换为JSON字符串
            const jsonBody = JSON.stringify(user);
            // 发送POST请求到/api/users添加新用户
            fetch('/api/users', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: jsonBody
            })
            .then(response => {
                if (response.ok) {
                    console.log('User added successfully.');
                    fetchUsers(); // 添加成功后更新用户列表
                } else {
                    console.error('Unable to add user.');
                }
            })
            .catch(error => console.error('Add user failed.', error));
        }
    </script>
</head>
<body>
    <button onclick="fetchUsers()">查询用户</button>
    <input type="text" id="new-user-name" placeholder="输入新用户名" />
    <button onclick="addUser(document.getElementById('new-user-name').value)">添加用户</button>
    <ul id="user-list"></ul>
</body>
</html>在这个例子中,我们定义了两个函数:fetchUsers 和 addUser。fetchUsers 使用AJAX的 fetch 方法从后端API /api/users 获取用户列表,然后更新页面上的用户列表。addUser 函数构建用户信息,将其转换为JSON格式,并通过POST方法发送到后端API /api/users 添加新用户,添加成功后同样更新用户列表。
评论已关闭