JS/PHP/MySQL过滤空值/零值商品列表的实现问题求助
Hey there! Let's tackle your problems step by step. You've got two main pain points here: manually populating each product by ID is tedious, and your script to hide empty items isn't working. Plus, there are some HTML syntax errors and mismatched IDs causing unexpected behavior. Let's fix all this together.
First, Fix the HTML Structure
Your original HTML has unclosed tags (like stray <span>s and misplaced <div>s) and duplicate IDs (e.g., gelatina is used twice). Let's clean that up and keep only the necessary containers for dynamic content:
<html lang="pt-br"> <head> <meta charset="utf-8"> <style> * { box-sizing: content-box; } li { display: block; margin: 8px 0; padding-left: 16px; } body { margin: 0; padding: 20px; background: lightgray; } .header h1 { color: black; background-color: #87c587; font-weight: italic; text-align: center; padding: 20px; font-size: 22px; border-radius: 8px; } #nome1 { font-weight: bold; font-size: 16px; } #status { color: darkred; text-align: center; margin-top: 15px; font-weight: bold; } .input-container { text-align: center; margin-top: 20px; } .input-container input { padding: 8px; margin-right: 8px; } </style> </head> <body> <div class="header"> <h1>lista de <span id="nome1"></span></h1> </div> <!-- Empty list where we'll dynamically add valid products --> <ul id="populate"></ul> <div class="input-container"> <input id="nome" name="nome" type="text" placeholder="Digite o nome"> <input type="submit" id="lstButton" name="lstButton" value="Confirmar nome"> </div> <div id="status"></div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> // Refactored jQuery code will go here </script> </body> </html>
Next, Refactor Ajax & Dynamic List Generation
Instead of manually updating each ID, we'll loop through the server's response, filter out invalid values (null/0/empty), and dynamically create list items only for valid products. This solves both the manual population and hiding problem in one go:
$(document).ready(function() { const url = "lista.php"; $('#lstButton').on('click', function(e) { e.preventDefault(); const nome = $.trim($("#nome").val()); const $productList = $('#populate'); const $status = $('#status'); const $nome1 = $('#nome1'); // Clear previous results and reset status $productList.empty(); $status.text(''); $nome1.text(nome); // Validate input first if (!nome) { $status.text("Por favor, digite um nome válido."); return; } $.ajax({ type: "POST", crossDomain: true, cache: false, url: url, dataType: 'json', data: { nome: nome }, success: function(data) { if (data.status === "success") { const products = data.result; let hasValidProducts = false; // Loop through all products in the server response for (const [productKey, value] of Object.entries(products)) { // Skip null, 0, or empty values if (value === null || value === 0 || value === '') { continue; } hasValidProducts = true; // Convert product keys to readable labels (e.g., "caldodecarne" → "Caldo de Carne") const readableName = productKey.replace(/([a-z])([A-Z])/g, '$1 $2') .replace(/de/g, ' de ') .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(' '); // Create and append the list item const $listItem = $('<li>').text(`${readableName}: ${value}`); $productList.append($listItem); } // Show message if no valid products exist if (!hasValidProducts) { $productList.append('<li>Nenhum produto válido encontrado.</li>'); } } else { $status.text("Erro ao carregar a lista."); } }, error: function() { $status.text("Falha na conexão com o servidor."); } }); }); });
Key Fixes & Improvements Explained
- Dynamic List Generation: Using
Object.entries()lets us loop through all products in the server response automatically. No more writing a line for each ID—new products from your database will appear without updating the JS. - Built-in Filtering: We skip any product with
null,0, or empty values before creating a list item. No need for a separate hide function! - HTML Cleanup: Fixed tag closing errors and duplicate IDs to eliminate unexpected behavior.
- User-Friendly Feedback: Added input validation, error states, and empty list messages to guide the user.
- Readable Product Names: The code converts database keys (like
caldodecarneormiojo) into clean, capitalized labels for better readability.
Why Your Original Script Failed
Your delNoSelectedProducts function had critical issues:
document.getElementsByTagName("LI").valueis invalid—this method returns a collection of elements, not a single element with avalueproperty.- You were checking the
<li>itself instead of the inner span/div content that holds the product value. - The function ran before the Ajax request finished, so there was no data to check yet.
By generating the list dynamically after the Ajax success, we avoid all these problems entirely.
内容的提问来源于stack exchange,提问作者mrx6s0

