面试题答案
一键面试<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户列表</title>
</head>
<body>
<div id="userList"></div>
<script>
const userListDiv = document.getElementById('userList');
fetch('/api/users')
.then(response => response.json())
.then(data => {
data.forEach(user => {
const p = document.createElement('p');
p.textContent = `姓名: ${user.name}, 年龄: ${user.age}`; // 假设用户对象有name和age属性
userListDiv.appendChild(p);
});
})
.catch(error => console.error('获取用户数据失败:', error));
</script>
</body>
</html>
上述代码中:
- 使用
fetch('/api/users')
发起对/api/users
接口的请求。 - 通过
.then(response => response.json())
将响应数据解析为 JSON 格式。 - 遍历获取到的数据,为每个用户创建一个
<p>
标签,并将用户信息展示在页面的userListDiv
中。 - 使用
.catch
捕获请求过程中可能出现的错误并在控制台打印。