You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 caldodecarne or miojo) into clean, capitalized labels for better readability.

Why Your Original Script Failed

Your delNoSelectedProducts function had critical issues:

  1. document.getElementsByTagName("LI").value is invalid—this method returns a collection of elements, not a single element with a value property.
  2. You were checking the <li> itself instead of the inner span/div content that holds the product value.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:17:50