本教程詳細(xì)介紹了如何使用JavaScript的Fetch API從遠(yuǎn)程接口獲取數(shù)據(jù),并將其動態(tài)渲染到HTML表格中。文章首先強調(diào)了理解API響應(yīng)數(shù)據(jù)結(jié)構(gòu)的重要性,隨后對比了兩種數(shù)據(jù)渲染方法:傳統(tǒng)的DOM操作和更高效的字符串模板結(jié)合`innerHTML`,并提供了完整的代碼示例和最佳實踐,旨在幫助開發(fā)者高效地實現(xiàn)前端數(shù)據(jù)展示。
在現(xiàn)代Web開發(fā)中,從遠(yuǎn)程API獲取數(shù)據(jù)并將其展示在網(wǎng)頁上是一項核心任務(wù)。JavaScript的Fetch API提供了一種強大且靈活的方式來執(zhí)行網(wǎng)絡(luò)請求。它基于Promise,使得處理異步操作更加簡潔。本教程將通過一個具體的例子,演示如何使用Fetch API獲取數(shù)據(jù),并將其動態(tài)渲染到一個HTML表格中。
我們將使用以下API端點作為示例:https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension。
在開始編寫代碼之前,理解API返回的數(shù)據(jù)結(jié)構(gòu)至關(guān)重要。一個常見的錯誤是直接假設(shè)API返回的數(shù)據(jù)就是我們需要的數(shù)組,而忽略了它可能被包裹在一個對象中。
立即學(xué)習(xí)“前端免費學(xué)習(xí)筆記(深入)”;
對于我們示例中的API,其響應(yīng)是一個JSON對象,其中包含一個名為webshops的數(shù)組。每個webshop對象都包含name_short、link、orig_url和logo_120x60等字段。
錯誤的初始假設(shè)(常見誤區(qū)):
// 假設(shè)數(shù)據(jù)直接是數(shù)組 [ { "name": "...", "url": "...", "logo": "..." }, // ... ]
正確的API響應(yīng)結(jié)構(gòu):
{ "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數(shù)據(jù)時,我們需要通過data.webshops來訪問實際的列表數(shù)據(jù),并且使用正確的字段名,如item.name_short而不是item.name。
這種方法通過JavaScript的document.createElement和appendChild等DOM操作方法,逐個創(chuàng)建HTML元素并將其添加到DOM樹中。
fetch('https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension') .then(response => response.json()) .then(({ webshops }) => { // 使用解構(gòu)賦值直接獲取webshops數(shù)組 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('獲取數(shù)據(jù)失敗:', error));
優(yōu)點:
缺點:
為了提高性能,尤其是處理大量數(shù)據(jù)時,推薦使用字符串模板(Template Literals)構(gòu)建完整的HTML字符串,然后一次性通過innerHTML屬性插入到DOM中。這種方法減少了與DOM的交互次數(shù)。
fetch('https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension') .then(response => response.json()) .then(({ webshops }) => { // 同樣使用解構(gòu)賦值 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(''); // 將數(shù)組中的HTML字符串拼接成一個大字符串 }) .catch(error => console.error('獲取數(shù)據(jù)失敗:', error));
優(yōu)點:
缺點:
為了使上述JavaScript代碼能夠正常運行,我們需要一個基本的HTML結(jié)構(gòu)來承載表格,以及一些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數(shù)據(jù)動態(tài)表格</title> <style> table { border-collapse: collapse; /* 合并邊框 */ width: 100%; /* 表格寬度占滿容器 */ margin-top: 20px; } th, td { padding: 12px 8px; /* 內(nèi)邊距 */ text-align: left; /* 文本左對齊 */ border-bottom: 1px solid #ddd; /* 底部邊框 */ } th { background-color: #f2f2f2; /* 表頭背景色 */ font-weight: bold; } tr:hover { background-color: #f5f5f5; /* 行懸停效果 */ } img { display: block; /* 避免圖片下方出現(xiàn)額外空白 */ } </style> </head> <body> <h1>API數(shù)據(jù)動態(tài)展示</h1> <table id="api-table"> <thead> <tr> <th>名稱</th> <th>鏈接</th> <th>Logo</th> </tr> </thead> <tbody> <!-- 數(shù)據(jù)將在此處動態(tài)加載 --> </tbody> </table> <script> // 將上述優(yōu)化后的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響應(yīng)中未找到webshops數(shù)組或其格式不正確。'); tableBody.innerHTML = '<tr><td colspan="3">暫無數(shù)據(jù)</td></tr>'; } }) .catch(error => { console.error('獲取或處理數(shù)據(jù)失敗:', error); document.querySelector('#api-table tbody').innerHTML = '<tr><td colspan="3" style="color:red;">加載數(shù)據(jù)失敗,請檢查網(wǎng)絡(luò)或API。</td></tr>'; }); </script> </body> </html>
通過本教程,我們學(xué)習(xí)了如何使用JavaScript的Fetch API從遠(yuǎn)程接口獲取JSON數(shù)據(jù),并將其動態(tài)渲染到HTML表格中。我們強調(diào)了理解API響應(yīng)結(jié)構(gòu)的重要性,并對比了兩種數(shù)據(jù)渲染方法:傳統(tǒng)的DOM操作和更高效的字符串模板結(jié)合innerHTML。在實際開發(fā)中,推薦使用后者來優(yōu)化性能,并始終牢記錯誤處理和安全性等最佳實踐,以構(gòu)建健壯且用戶友好的Web應(yīng)用。
以上就是使用Fetch API在HTML中動態(tài)獲取并渲染表格數(shù)據(jù)的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
HTML怎么學(xué)習(xí)?HTML怎么入門?HTML在哪學(xué)?HTML怎么學(xué)才快?不用擔(dān)心,這里為大家提供了HTML速學(xué)教程(入門課程),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號