前端获取数据库数据在页面中展示怎么实现
时间: 2024-03-01 20:49:45 浏览: 31
前端获取数据库数据有多种方式,常见的有以下几种:
1. 使用 Ajax 发起 HTTP 请求,后端返回 JSON 格式的数据,前端解析并渲染页面。
2. 使用 WebSocket 进行实时通信,后端将数据库更新时的数据实时推送给前端,前端渲染页面。
3. 使用 GraphQL 进行数据查询,后端返回符合查询条件的数据,前端使用 GraphQL Client 解析并渲染页面。
以下是一个使用 Ajax 获取数据库数据并在页面中展示的示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>获取数据库数据并在页面中展示</title>
</head>
<body>
<table>
<thead>
<tr>
<th>名称</th>
<th>得分</th>
</tr>
</thead>
<tbody id="scoreboard">
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 发起 Ajax 请求获取数据
axios.get('/api/scoreboard')
.then(response => {
// 解析数据并渲染页面
const scoreboard = document.getElementById('scoreboard')
const data = response.data
for (let i = 0; i < data.length; i++) {
const row = document.createElement('tr')
const name = document.createElement('td')
const score = document.createElement('td')
name.innerText = data[i].name
score.innerText = data[i].score
row.appendChild(name)
row.appendChild(score)
scoreboard.appendChild(row)
}
})
.catch(error => {
console.error(error)
})
</script>
</body>
</html>
```
在上述代码中,我们使用 Axios 发起了一个 GET 请求,获取 `/api/scoreboard` 接口返回的数据,并使用 JavaScript 动态创建了一个 HTML 表格来展示数据。具体来说,我们首先在 HTML 中定义了一个空的表格,然后在 JavaScript 中使用 `document.createElement` 方法创建了表格中的每个单元格,并使用 `appendChild` 方法将单元格添加到表格中。最终得到的结果是一个包含了数据库数据的 HTML 表格。