
本教程旨在指导如何使用javascript从api获取数据,并在网页表格中动态展示。核心内容包括数据全局存储、利用`array.prototype.filter()`方法实现高效的数据搜索功能,并根据用户输入实时更新表格内容,同时强调代码结构优化和大小写不敏感的搜索实现。
在现代前端应用中,从API获取数据并以交互式表格的形式呈现是常见的需求。当数据量较大时,用户需要一个搜索功能来快速定位所需信息。本文将详细介绍如何利用JavaScript实现这一功能,包括数据获取、全局存储、动态表格渲染以及基于用户输入的实时搜索过滤。
实现这一功能主要依赖以下JavaScript核心技术:
首先,我们需要构建基础的HTML骨架,包括一个输入框用于用户输入搜索关键词,一个搜索按钮来触发搜索,以及一个表格来展示数据。
<!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>
/* 简单的样式,可根据需要自行美化 */
body { font-family: Arial, sans-serif; margin: 20px; }
input[type="text"], input[type="submit"] { padding: 8px; margin-bottom: 10px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<!-- 搜索框与搜索按钮 -->
<input type="text" id="myInput" placeholder=" 搜索国家 ">
<input type="submit" id="mySubmit" value="搜索" class="submit">
<!-- 数据表格 -->
<table class="table">
<thead>
<tr>
<th scope="col">国家</th>
<th scope="col">新增确诊</th>
<th scope="col">累计确诊</th>
<th scope="col">新增死亡</th>
<th scope="col">累计死亡</th>
<th scope="col">新增恢复</th>
<th scope="col">累计恢复</th>
<th scope="col">最后更新日期</th>
</tr>
</thead>
<tbody id="tbody">
<!-- 数据将通过JavaScript动态加载到这里 -->
</tbody>
</table>
<script src="script.js"></script> <!-- 引入JavaScript文件 -->
</body>
</html>注意: 确保输入框 (myInput)、搜索按钮 (mySubmit) 和表格主体 (tbody) 都具有唯一的 id 属性,以便JavaScript能够准确地获取并操作它们。
立即学习“Java免费学习笔记(深入)”;
为了实现搜索功能,我们需要在首次从API获取数据后,将其存储在一个全局可访问的变量中。这样,每次用户进行搜索时,我们就不需要重新请求API,而是直接对已有的数据进行过滤。
// script.js
let countriesData = []; // 全局变量,用于存储从API获取的所有国家数据
/**
* 从API获取数据并初始化全局变量
*/
const getdata = async () => {
const endpoint = "https://api.covid19api.com/summary";
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// 将获取到的国家数据存储到全局变量
countriesData = data.Countries;
// 数据加载完成后,立即显示所有国家数据
_DisplayCountries();
} catch (error) {
console.error("获取数据失败:", error);
// 可以在这里添加错误提示给用户
}
};
// 在页面加载完成后调用数据获取函数
getdata();在上述代码中:
接下来,我们创建一个函数来负责数据的过滤和表格的渲染。这个函数将接受一个可选的搜索关键词作为参数。
// script.js (接上一段代码)
/**
* 根据搜索关键词过滤并显示国家数据
* @param {string} searchTerm - 用户输入的搜索关键词,默认为空字符串表示显示所有数据
*/
const _DisplayCountries = (searchTerm = "") => {
const tbody = document.querySelector("#tbody");
tbody.innerHTML = ``; // 清空现有表格内容
// 使用filter方法根据搜索关键词筛选数据
const filteredCountries = countriesData.filter(country =>
country.Country.toLowerCase().includes(searchTerm.toLowerCase())
);
// 遍历筛选后的数据,并将其添加到表格中
filteredCountries.forEach(result => {
tbody.innerHTML += `<tr>
<td>${result.Country}</td>
<td>${result.NewConfirmed}</td>
<td>${result.TotalConfirmed}</td>
<td>${result.NewDeaths}</td>
<td>${result.TotalDeaths}</td>
<td>${result.NewRecovered}</td>
<td>${result.TotalRecovered}</td>
<td>${result.Date}</td>
</tr>`;
});
// 如果没有搜索结果,可以显示提示信息
if (filteredCountries.length === 0 && searchTerm !== "") {
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">没有找到匹配 "${searchTerm}" 的国家。</td></tr>`;
}
};_DisplayCountries 函数的实现细节:
最后一步是为搜索按钮添加事件监听器,当用户点击按钮时,获取输入框中的值并调用 _DisplayCountries 函数来更新表格。
// script.js (接上一段代码)
// 为搜索按钮添加点击事件监听器
document.querySelector("#mySubmit").addEventListener("click", () => {
const searchInput = document.querySelector("#myInput").value;
_DisplayCountries(searchInput); // 将搜索框的值作为参数传递给显示函数
});
// 也可以为输入框添加 'keyup' 事件,实现实时搜索
document.querySelector("#myInput").addEventListener("keyup", (event) => {
// 只有在用户按下Enter键时才搜索,或者实时搜索
// if (event.key === "Enter") {
const searchInput = document.querySelector("#myInput").value;
_DisplayCountries(searchInput);
// }
});将上述HTML和JavaScript代码整合后,您将得到一个功能完整的可搜索数据表格。
HTML (index.html):
<!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>
body { font-family: Arial, sans-serif; margin: 20px; }
input[type="text"], input[type="submit"] { padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { background-color: #007bff; color: white; cursor: pointer; }
input[type="submit"]:hover { background-color: #0056b3; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
tr:nth-child(even) { background-color: #f9f9f9; }
</style>
</head>
<body>
<input type="text" id="myInput" placeholder=" 搜索国家 ">
<input type="submit" id="mySubmit" value="搜索" class="submit">
<table class="table">
<thead>
<tr>
<th scope="col">国家</th>
<th scope="col">新增确诊</th>
<th scope="col">累计确诊</th>
<th scope="col">新增死亡</th>
<th scope="col">累计死亡</th>
<th scope="col">新增恢复</th>
<th scope="col">累计恢复</th>
<th scope="col">最后更新日期</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<script src="script.js"></script>
</body>
</html>JavaScript (script.js):
let countriesData = [];
const getdata = async () => {
const endpoint = "https://api.covid19api.com/summary";
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
countriesData = data.Countries;
_DisplayCountries(); // 初始显示所有数据
} catch (error) {
console.error("获取数据失败:", error);
const tbody = document.querySelector("#tbody");
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: red;">数据加载失败,请稍后再试。</td></tr>`;
}
};
const _DisplayCountries = (searchTerm = "") => {
const tbody = document.querySelector("#tbody");
tbody.innerHTML = ``; // 清空现有表格内容
const filteredCountries = countriesData.filter(country =>
country.Country.toLowerCase().includes(searchTerm.toLowerCase())
);
if (filteredCountries.length === 0 && searchTerm !== "") {
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">没有找到匹配 "${searchTerm}" 的国家。</td></tr>`;
return;
}
filteredCountries.forEach(result => {
tbody.innerHTML += `<tr>
<td>${result.Country}</td>
<td>${result.NewConfirmed}</td>
<td>${result.TotalConfirmed}</td>
<td>${result.NewDeaths}</td>
<td>${result.TotalDeaths}</td>
<td>${result.NewRecovered}</td>
<td>${result.TotalRecovered}</td>
<td>${result.Date}</td>
</tr>`;
});
};
// 页面加载时获取数据
getdata();
// 搜索按钮点击事件
document.querySelector("#mySubmit").addEventListener("click", () => {
const searchInput = document.querySelector("#myInput").value;
_DisplayCountries(searchInput);
});
// 输入框实时搜索事件 (可选)
document.querySelector("#myInput").addEventListener("keyup", () => {
const searchInput = document.querySelector("#myInput").value;
_DisplayCountries(searchInput);
});大小写不敏感搜索的替代方案:正则表达式 除了使用 toLowerCase() 和 includes(),您还可以使用正则表达式来实现更灵活的搜索模式,例如:
// 在 _DisplayCountries 函数内部
const regex = new RegExp(searchTerm, "i"); // "i" 标志表示不区分大小写
const filteredCountries = countriesData.filter(country =>
country.Country.match(regex)
);这种方法在需要更复杂的模式匹配时(例如匹配开头、结尾、或使用特定字符集)会更加强大。
性能优化 对于非常庞大的数据集(例如数万甚至数十万条记录),每次 innerHTML 的重新赋值可能会导致性能问题。此时可以考虑:
用户体验
错误处理 在 getdata 函数中,我们已经添加了基本的 try...catch 块来捕获API请求错误。在实际应用中,您可能需要更详细的错误信息展示给用户。
代码分离与模块化 对于更复杂的应用,可以将数据获取、渲染逻辑和事件处理进一步封装到不同的模块或类中,提高代码的可维护性和复用性。
通过本教程,我们学习了如何利用JavaScript的Fetch API获取远程数据,并将其存储在全局变量中。核心搜索功能通过 Array.prototype.filter() 结合 toLowerCase() 和 includes() 方法实现,确保了大小写不敏感的模糊匹配。同时,通过动态更新DOM,实现了用户输入后表格内容的实时刷新。遵循代码分离的原则,将数据获取和数据展示逻辑封装在不同的函数中,有助于提升代码的可读性和可维护性。这些技术是构建交互式前端数据展示应用的基础。
以上就是JavaScript实现API数据搜索与动态表格展示的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号