
本教程详细讲解如何使用javascript实现前端数据搜索功能。通过从api获取数据并将其存储,我们演示了如何利用`Array.prototype.Filter()`方法根据用户输入动态筛选数据,并实时更新html表格内容。文章涵盖了数据获取、存储、渲染以及搜索逻辑的实现,并提供了完整的代码示例和优化建议,帮助开发者构建高效的用户界面。
在现代Web应用中,从API获取大量数据并提供用户友好的搜索功能是常见的需求。本教程将指导您如何使用纯javaScript实现这一功能,包括数据获取、本地存储、动态渲染以及基于用户输入的搜索过滤。
核心思路
实现前端数据搜索功能的核心在于以下几点:
- 一次性获取并存储所有数据: 避免每次搜索都重新请求API,提高效率。将获取到的完整数据集存储在一个可访问的变量中。
- 职责分离: 将数据获取、数据渲染和搜索逻辑分离为独立的函数,提高代码的可维护性和复用性。
- 动态过滤: 利用javascript数组的filter()方法,根据用户输入筛选出匹配的数据子集。
- 动态更新ui: 每次筛选后,清空并重新填充html表格,展示过滤后的数据。
HTML结构准备
首先,我们需要一个包含搜索框、搜索按钮和数据展示表格的基础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: sans-serif; margin: 20px; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } input[type="text"], input[type="submit"] { padding: 8px; margin-right: 5px; } input[type="submit"] { cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 4px; } input[type="submit"]:hover { background-color: #0056b3; } </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="app.js"></script> <!-- 假设JavaScript代码在app.js中 --> </body> </html>
数据获取与存储
我们将从一个公共API(例如COVID-19 API)获取国家疫情数据。关键在于将获取到的Countries数组存储在一个全局变量中,以便后续的搜索和过滤操作能够访问到完整的数据集。
立即学习“Java免费学习笔记(深入)”;
// app.js // 用于存储从API获取的完整国家数据 let countriesData = []; /** * 从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();
数据展示函数
为了避免代码重复,我们创建一个专门的函数来负责将数据渲染到HTML表格中。这个函数可以接受一个可选的参数,用于指定要展示的数据子集(例如,搜索结果)。
// app.js (接上文) /** * 将国家数据显示到表格中 * @param {String} searchTerm - 可选的搜索关键词,用于过滤国家名称 */ const _DisplayCountries = (searchTerm = "") => { const tbody = document.querySelector("#tbody"); tbody.innerHTML = ``; // 清空现有表格内容 // 根据搜索词过滤数据,如果searchTerm为空,则显示所有数据 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>${new date(result.Date).toLocaleString()}</td> </tr> `; }); };
在_DisplayCountries函数中,我们对Date字段进行了格式化,使其更具可读性。
实现搜索逻辑
现在,我们将为搜索按钮添加事件监听器。当用户点击搜索按钮时,我们将获取搜索框中的值,并将其传递给_DisplayCountries函数,从而实现数据的过滤和更新。
// app.js (接上文) // 获取搜索按钮和输入框 const searchInput = document.querySelector("#myInput"); const searchButton = document.querySelector("#mySubmit"); // 为搜索按钮添加点击事件监听器 searchButton.addEventListener("click", () => { const searchTerm = searchInput.value.trim(); // 获取并去除输入值两端的空白 _DisplayCountries(searchTerm); // 调用显示函数,传入搜索词 }); // 也可以为输入框添加 'input' 事件监听器,实现实时搜索 searchInput.addEventListener("input", () => { const searchTerm = searchInput.value.trim(); _DisplayCountries(searchTerm); });
这里我们同时为搜索按钮的click事件和搜索输入框的input事件添加了监听器。这意味着用户可以点击按钮进行搜索,也可以在输入时实时看到结果更新,这通常能提供更好的用户体验。
完整代码示例
将上述所有JavaScript代码整合到一个文件中(例如app.js),并确保html文件正确引用它。
// app.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 _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>${new Date(result.Date).toLocaleString()}</td> </tr> `; }); }; getdata(); const searchInput = document.querySelector("#myInput"); const searchButton = document.querySelector("#mySubmit"); searchButton.addEventListener("click", () => { const searchTerm = searchInput.value.trim(); _DisplayCountries(searchTerm); }); searchInput.addEventListener("input", () => { const searchTerm = searchInput.value.trim(); _DisplayCountries(searchTerm); });
优化与注意事项
- 大小写不敏感搜索: 在上述代码中,我们使用了toLowerCase()方法将国家名称和搜索词都转换为小写,确保搜索是大小写不敏感的,提高了用户体验。
- 替代搜索方法: String.prototype.includes()是一个简单有效的匹配方法。对于更复杂的搜索模式(例如,只匹配开头、精确匹配等),可以使用正则表达式:
// 使用正则表达式进行搜索 // let regex = new RegExp(searchTerm, "i"); // "i" 标志表示不区分大小写 // countriesData.filter(country => country.Country.match(regex))
- 用户体验:
- 实时搜索: 为input元素添加input事件监听器,可以实现在用户输入时即时更新搜索结果,提供更流畅的体验。
- 空搜索结果提示: 当搜索结果为空时,可以在表格中显示一条友好的提示信息,而不是空白表格。
- 性能考量:
- 对于小型到中型数据集(几千到几万条),客户端JavaScript的filter()方法通常足够高效。
- 对于非常庞大的数据集(数十万甚至更多),客户端过滤可能会导致性能瓶颈。在这种情况下,考虑将搜索逻辑放在服务器端实现(即每次搜索都向API发送带有搜索参数的请求),由服务器返回过滤后的数据。
- 错误处理: 在getdata函数中增加了try…catch块来捕获API请求可能发生的错误,并打印到控制台。在实际应用中,您可能需要向用户显示更友好的错误消息。
总结
通过本教程,我们学习了如何构建一个基于API数据的动态搜索功能。关键在于高效地获取并存储数据,利用filter()方法进行客户端筛选,并通过专门的函数动态更新UI。这种模式不仅适用于表格数据,也适用于任何需要动态过滤和展示列表数据的场景,为用户提供了灵活且响应迅速的数据探索体验。