使用html如何通过调用后端接口动态生成表格
时间: 2023-12-30 21:05:53 浏览: 27
可以通过使用 JavaScript 发送 AJAX 请求来调用后端接口,获取返回的数据,并且使用 DOM 操作动态生成表格。
下面是一个简单的示例代码:
HTML:
```html
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
```
JavaScript:
```javascript
// 发送 AJAX 请求获取数据
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/users');
xhr.onload = function() {
if (xhr.status === 200) {
const users = JSON.parse(xhr.responseText);
// 动态生成表格内容
const tbody = document.querySelector('#myTable tbody');
users.forEach(function(user) {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
`;
tbody.appendChild(tr);
});
} else {
console.error('Failed to get users');
}
};
xhr.send();
```
在上面的代码中,我们使用 XMLHttpRequest 对象发送 GET 请求到后端接口 `/api/users`,并且在请求成功后解析返回的 JSON 数据,使用 DOM 操作动态生成表格内容。需要注意的是,我们需要将表格内容生成在 `<tbody>` 标签中,而不是 `<thead>` 标签中,这样才能正确地显示表格。