按类别展示JSON数据异常:选中All类别无法显示全部内容
问题:选中「All」类别无法展示全部JSON数据
页面实现了按类别筛选JSON数据的功能,选中具体类别(如Fruits、Vegetables)时功能正常,但选择「All」选项时无法显示所有数据。
问题定位
问题出在前端app.js的二次过滤逻辑:
当选中「All」时,category值为字符串"all",原代码中if (category)条件会成立(非空字符串为真),进而执行data.filter(item => item.category == category)。但所有数据项的category字段都是"fruits"/"vegetables"/"dairy",没有与"all"匹配的项,最终过滤后得到空数组,导致页面无内容。
后端app.php的逻辑是正确的,当传入category=all时会返回全量JSON数据,但前端的错误过滤把数据清空了。
修复方案
修改app.js中的过滤逻辑,仅当选中的类别不是"all"时才执行过滤:
// Wait for the DOM to finish loading document.addEventListener("DOMContentLoaded", function() { // Get references to the category select element and category container element var categorySelect = document.getElementById("category-select"); var categoryContainer = document.getElementById("category-container"); // Attach an event listener to the category select element categorySelect.addEventListener("change", function() { // Get the selected category var category = categorySelect.value; // Send an AJAX request to the server to get the data for the selected category var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Parse the JSON response var data = JSON.parse(xhr.responseText); // Filter the data by the selected category - 修复此处逻辑 if (category && category!== "all") { // 新增判断,排除"all"情况 data = data.filter(function(item) { return item.category == category; }); } // Build the HTML to display the filtered data var html = ""; data.forEach(function(item) { html += "<h2>" + item.name + "</h2>"; html += "<p>" + item.description + "</p>"; }); // Update the category container with the HTML categoryContainer.innerHTML = html; } }; xhr.open("GET", "app.php?category=" + encodeURIComponent(category), true); xhr.send(); }); });
可选优化
可以统一过滤逻辑到前端,简化后端app.php的代码,避免前后端重复过滤:
直接让后端返回全量数据,所有筛选逻辑由前端处理,后端代码可简化为:
<?php // Read the contents of the data.json file $data = file_get_contents('data.json'); // Set the content type header to indicate that we are sending JSON data header('Content-Type: application/json'); // Send the full data as JSON echo $data;
内容的提问来源于stack exchange,提问作者uzxzn
相关产品推荐
相关产品推荐

