
本教程详细介绍了如何使用JavaScript的Fetch API从远程接口获取数据,并将其动态渲染到HTML表格中。文章首先强调了理解API响应数据结构的重要性,随后对比了两种数据渲染方法:传统的DOM操作和更高效的字符串模板结合`innerHTML`,并提供了完整的代码示例和最佳实践,旨在帮助开发者高效地实现前端数据展示。
在现代Web开发中,从远程API获取数据并将其展示在网页上是一项核心任务。JavaScript的Fetch API提供了一种强大且灵活的方式来执行网络请求。它基于Promise,使得处理异步操作更加简洁。本教程将通过一个具体的例子,演示如何使用Fetch API获取数据,并将其动态渲染到一个HTML表格中。
我们将使用以下API端点作为示例:https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension。
在开始编写代码之前,理解API返回的数据结构至关重要。一个常见的错误是直接假设API返回的数据就是我们需要的数组,而忽略了它可能被包裹在一个对象中。
立即学习“前端免费学习笔记(深入)”;
对于我们示例中的API,其响应是一个JSON对象,其中包含一个名为webshops的数组。每个webshop对象都包含name_short、link、orig_url和logo_120x60等字段。
错误的初始假设(常见误区):
// 假设数据直接是数组
[
{ "name": "...", "url": "...", "logo": "..." },
// ...
]正确的API响应结构:
{
"webshops": [
{
"id": "...",
"name_short": "Webshop A",
"link": "https://link.to/webshopA",
"orig_url": "https://original.url/webshopA",
"logo_120x60": "https://logo.url/webshopA.png",
// ...其他字段
},
{
"id": "...",
"name_short": "Webshop B",
"link": "https://link.to/webshopB",
"orig_url": "https://original.url/webshopB",
"logo_120x60": "https://logo.url/webshopB.png",
// ...其他字段
}
// ...
]
}因此,在处理fetch返回的JSON数据时,我们需要通过data.webshops来访问实际的列表数据,并且使用正确的字段名,如item.name_short而不是item.name。
这种方法通过JavaScript的document.createElement和appendChild等DOM操作方法,逐个创建HTML元素并将其添加到DOM树中。
fetch('https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension')
.then(response => response.json())
.then(({ webshops }) => { // 使用解构赋值直接获取webshops数组
const tableBody = document.querySelector('#api-table tbody');
webshops.forEach(item => {
const row = document.createElement('tr');
const nameCell = document.createElement('td');
nameCell.textContent = item.name_short; // 使用正确的字段名
row.appendChild(nameCell);
const urlCell = document.createElement('td');
const urlLink = document.createElement('a');
urlLink.href = item.link; // 使用正确的字段名
urlLink.textContent = item.orig_url; // 使用正确的字段名
urlCell.appendChild(urlLink);
row.appendChild(urlCell);
const logoCell = document.createElement('td');
const logoImg = document.createElement('img');
logoImg.src = item.logo_120x60; // 使用正确的字段名
logoImg.alt = item.name_short;
logoImg.style.maxWidth = '100px';
logoCell.appendChild(logoImg);
row.appendChild(logoCell);
tableBody.appendChild(row);
});
})
.catch(error => console.error('获取数据失败:', error));优点:
缺点:
为了提高性能,尤其是处理大量数据时,推荐使用字符串模板(Template Literals)构建完整的HTML字符串,然后一次性通过innerHTML属性插入到DOM中。这种方法减少了与DOM的交互次数。
fetch('https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension')
.then(response => response.json())
.then(({ webshops }) => { // 同样使用解构赋值
const tableBody = document.querySelector('#api-table tbody');
tableBody.innerHTML = webshops.map(item =>
`<tr>
<td>${item.name_short}</td>
<td><a href="${item.link}">${item.orig_url}</a></td>
<td>
<img src="${item.logo_120x60}"
style="max-width:100px"
alt="${item.name_short}">
</td>
</tr>`
).join(''); // 将数组中的HTML字符串拼接成一个大字符串
})
.catch(error => console.error('获取数据失败:', error));优点:
缺点:
为了使上述JavaScript代码能够正常运行,我们需要一个基本的HTML结构来承载表格,以及一些CSS样式来美化表格。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API数据动态表格</title>
<style>
table {
border-collapse: collapse; /* 合并边框 */
width: 100%; /* 表格宽度占满容器 */
margin-top: 20px;
}
th, td {
padding: 12px 8px; /* 内边距 */
text-align: left; /* 文本左对齐 */
border-bottom: 1px solid #ddd; /* 底部边框 */
}
th {
background-color: #f2f2f2; /* 表头背景色 */
font-weight: bold;
}
tr:hover {
background-color: #f5f5f5; /* 行悬停效果 */
}
img {
display: block; /* 避免图片下方出现额外空白 */
}
</style>
</head>
<body>
<h1>API数据动态展示</h1>
<table id="api-table">
<thead>
<tr>
<th>名称</th>
<th>链接</th>
<th>Logo</th>
</tr>
</thead>
<tbody>
<!-- 数据将在此处动态加载 -->
</tbody>
</table>
<script>
// 将上述优化后的JavaScript代码(方法二)放入此处
fetch('https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(({ webshops }) => {
const tableBody = document.querySelector('#api-table tbody');
if (webshops && Array.isArray(webshops)) {
tableBody.innerHTML = webshops.map(item =>
`<tr>
<td>${item.name_short}</td>
<td><a href="${item.link}" target="_blank">${item.orig_url}</a></td>
<td>
<img src="${item.logo_120x60}"
style="max-width:100px; height:auto;"
alt="${item.name_short}">
</td>
</tr>`
).join('');
} else {
console.warn('API响应中未找到webshops数组或其格式不正确。');
tableBody.innerHTML = '<tr><td colspan="3">暂无数据</td></tr>';
}
})
.catch(error => {
console.error('获取或处理数据失败:', error);
document.querySelector('#api-table tbody').innerHTML = '<tr><td colspan="3" style="color:red;">加载数据失败,请检查网络或API。</td></tr>';
});
</script>
</body>
</html>通过本教程,我们学习了如何使用JavaScript的Fetch API从远程接口获取JSON数据,并将其动态渲染到HTML表格中。我们强调了理解API响应结构的重要性,并对比了两种数据渲染方法:传统的DOM操作和更高效的字符串模板结合innerHTML。在实际开发中,推荐使用后者来优化性能,并始终牢记错误处理和安全性等最佳实践,以构建健壮且用户友好的Web应用。
以上就是使用Fetch API在HTML中动态获取并渲染表格数据的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号