js html实现接口数据加载至前端表格中
时间: 2023-11-28 20:48:58 浏览: 53
可以使用 AJAX 技术从后端接口获取数据,然后使用 JavaScript 将数据渲染到前端表格中。以下是一个简单的示例:
HTML 代码:
```html
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
```
JavaScript 代码:
```javascript
// 发送 AJAX 请求并将数据渲染到表格中
function loadData() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
renderTable(data);
} else {
console.log("Error: " + xhr.status);
}
}
};
xhr.open("GET", "/api/data", true);
xhr.send();
}
// 渲染表格
function renderTable(data) {
var table = document.getElementById("myTable");
var tbody = table.querySelector("tbody");
tbody.innerHTML = ""; // 先清空表格
data.forEach(function(row) {
var tr = document.createElement("tr");
tr.innerHTML = "<td>" + row.id + "</td>" +
"<td>" + row.name + "</td>" +
"<td>" + row.age + "</td>";
tbody.appendChild(tr);
});
}
// 页面加载时加载数据
window.onload = function() {
loadData();
};
```
在这个例子中,我们使用了 XMLHttpRequest 对象来发送异步请求,请求后端的 `/api/data` 接口获取数据。在接收到数据后,我们使用 `JSON.parse` 将 JSON 格式的字符串转换为 JavaScript 对象,并将数据传递给 `renderTable` 函数。该函数动态创建表格行并将数据渲染到表格中。
注意,这个例子仅用于演示如何从后端接口获取数据并将其渲染到前端表格中。在实际应用中,您需要根据具体的接口返回的数据格式和表格结构进行调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)