html get 数据填充表格
时间: 2023-12-20 08:07:47 浏览: 40
要将数据填充到 HTML 表格中,您需要使用 JavaScript 来获取数据并将其插入到表格中。以下是一个示例代码片段,它通过 AJAX 请求获取数据,并将其填充到表格中:
```html
<table id="myTable">
<thead>
<tr>
<th>名字</th>
<th>年龄</th>
<th>地址</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
var table = document.getElementById("myTable");
var tbody = table.getElementsByTagName("tbody")[0];
for (var i = 0; i < data.length; i++) {
var row = tbody.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = data[i].name;
cell2.innerHTML = data[i].age;
cell3.innerHTML = data[i].address;
}
}
};
xhttp.open("GET", "data.json", true);
xhttp.send();
</script>
```
在此示例中,我们使用了 AJAX 请求来获取数据。当请求成功时,我们使用 JavaScript 将数据插入到表格中。请注意,我们使用了 `insertRow` 和 `insertCell` 方法来创建新行和单元格,并使用 `innerHTML` 方法将数据填充到单元格中。同时,我们也将表头和表身区分开来,以便更好地管理表格。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)