在JavaScript中加载表格数据通常涉及以下几个基础概念:
以下是一个使用Fetch API从服务器获取JSON数据并填充到HTML表格中的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Load Table Data</title>
</head>
<body>
<table id="dataTable" border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<!-- Data will be loaded here -->
</tbody>
</table>
<script src="script.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', function() {
fetch('https://api.example.com/users') // 替换为实际的API地址
.then(response => response.json())
.then(data => {
const tableBody = document.querySelector('#dataTable tbody');
data.forEach(user => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
`;
tableBody.appendChild(row);
});
})
.catch(error => console.error('Error fetching data:', error));
});
JSON.stringify
和JSON.parse
来处理JSON数据。.catch
方法捕获错误并进行相应处理。Access-Control-Allow-Origin
。.catch
方法捕获并处理错误。通过以上方法,可以实现JavaScript动态加载表格数据,并处理常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云