如何将API GET响应数据填充至HTML表格?JS新手技术求助
实现方案:调用接口生成课程信息表格
直接给你能跑的完整代码,分两部分说明:
HTML 结构
先搭好表格的基础框架,表头对应接口返回的字段,tbody留空用来动态填充数据:
<!DOCTYPE html> <html lang="hr"> <head> <meta charset="UTF-8"> <title>课程列表</title> <style> table { border-collapse: collapse; width: 80%; margin: 20px auto; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <h1>课程列表</h1> <table> <thead> <tr> <th>课程名称</th> <th>ECTS学分</th> <th>学期</th> </tr> </thead> <tbody id="courseTableBody"></tbody> </table> <script> // 这里可以直接写JS逻辑,或者单独放js文件 </script> </body> </html>
JavaScript 逻辑
用原生fetch发送GET请求,处理接口返回的数据,然后生成表格行插入到tbody中:
// 获取表格tbody元素 const tableBody = document.getElementById('courseTableBody'); // 调用接口 fetch('https://www.fulek.com/data/api/supit/curriculum-list/hr') .then(response => { // 检查请求是否成功 if (!response.ok) { throw new Error(`请求失败:${response.status}`); } return response.json(); }) .then(courses => { // 清空tbody(防止重复加载) tableBody.innerHTML = ''; // 遍历课程数组,生成每一行 courses.forEach(course => { const row = document.createElement('tr'); // 创建单元格并填充数据 const nameCell = document.createElement('td'); nameCell.textContent = course.kolegij; row.appendChild(nameCell); const ectsCell = document.createElement('td'); ectsCell.textContent = course.ects; row.appendChild(ectsCell); // 处理学期字段 const semesterCell = document.createElement('td'); semesterCell.textContent = course.semestar; row.appendChild(semesterCell); // 将行添加到tbody tableBody.appendChild(row); }); }) .catch(error => { // 处理错误,显示错误信息 tableBody.innerHTML = `<tr><td colspan="3">加载课程失败:${error.message}</td></tr>`; console.error(error); });
关键注意点
- 所有DOM操作必须放在
fetch的.then()回调里,因为请求是异步的,不能提前操作还没加载好的数据 - 用
createElement创建DOM元素比直接拼接HTML字符串更安全,避免XSS风险 - 一定要处理请求失败的情况,比如网络中断、接口返回错误状态码
- 如果接口返回的字段有增减,直接调整对应的
course.xxx即可
内容的提问来源于stack exchange,提问作者repinSlun
相关产品推荐
相关产品推荐

