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

PHP循环中Checkbox的order-id与product-quantity属性动态设置问题求助

解决循环中复选框动态属性无法正确获取的问题

问题描述

在订单处理页面中,点击「确认处理」按钮触发updateNonManquant函数时,循环内无法正确获取对应订单下复选框的data-order-id和data-product-quantity属性,导致后续业务逻辑无法正常执行。

问题根源

  1. 复选框ID全局冲突:后端PHP中$checkbox_id是全局递增变量,所有订单的复选框ID连续累加;但前端JS循环时,仅根据当前订单的产品数量从0开始取ID,会错误获取到页面中前N个复选框(属于其他订单),而非当前订单下的目标元素。
  2. 冗余的判断逻辑:代码中用button.includes(order_id)做匹配完全多余,反而可能因类型不匹配导致判断失效。

修复方案

1. 后端PHP代码调整

修改复选框渲染逻辑,给每个订单下的复选框绑定订单ID标识,同时简化按钮传参:

<?php
    require_once "process_orders.php";
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>客户订单处理</title>
        <link rel="stylesheet" href="style.css">
        <script src="updateNonManquant_function.js"></script>
    </head>

    <body>
        <?php
        if ($number_of_orders == 0)
        {
            ?>
            <div class="centerPage">
                <h1>暂无待处理订单</h1>
            </div>
            <?php
        }
        else
        {
            ?>
            <h1 class="centerMargin">订单处理</h1>
            <?php

            for ($i = 0; $i < $number_of_orders; $i++) 
            {
                $current_order_id = $customerOrder[$i]->getOrder_id();
                ?>
                <div class="order-container" data-order-id="<?= $current_order_id ?>">
                    <table>
                        <tr>
                            <th colspan="3"><?= $customerOrder[$i]->getName(); ?></th>
                        </tr>
                        <tr>
                            <th>产品</th>
                            <th>数量</th>
                            <th><?= $customerOrder[$i]->getOrder_date(); ?></th>
                        </tr>
                        <?php
                        for ($j = 0; $j < $customerOrder[$i]->getTotalProducts(); $j++)
                        {
                            $product_name = $customerOrder[$i]->getProductName($j);
                            $product_quantity = $customerOrder[$i]->getProductQuantity($j);
                            $product_id = $customerOrder[$i]->getProductId($j);
                            ?>
                            <tr>
                                <td><?= $product_name; ?></td>
                                <td><?= $product_quantity; ?></td>
                                <td>
                                    <input type="checkbox" 
                                           name="<?= $product_id ;?>" 
                                           class="checkbox" 
                                           data-order-id="<?= $current_order_id; ?>" 
                                           data-product-quantity="<?= $product_quantity; ?>"
                                           <?= $customerOrder[$i]->getProductAvailable($j) == "true" ? "checked" : ""; ?>>
                                </td>
                            </tr>
                            <?php
                        }
                        ?>
                    </table>
                    <table style="border-color: transparent;">
                        <tr>
                            <th colspan="3" style="background-color : transparent;">
                                <button onclick="updateNonManquant(<?= $current_order_id; ?>)">确认处理</button>
                            </th>
                        </tr>
                    </table>
                </div>
                <br> <br>
                <?php
            }
        }
        ?>
    </body>
</html>

2. 前端JS代码重构

修改updateNonManquant函数,直接通过订单ID筛选对应复选框,彻底避免全局ID的匹配错误:

function updateNonManquant(order_id)
{
    // 精准获取当前订单下的所有复选框
    const checkboxes = document.querySelectorAll(`.checkbox[data-order-id="${order_id}"]`);
    const date = new Date().toISOString().slice(0, 19).replace('T', ' ');

    checkboxes.forEach(checkbox => {
        const product_id = checkbox.name;
        // 使用dataset访问data属性,更符合现代JS规范
        const product_quantity = checkbox.dataset.productQuantity;

        let xhr = makeRequest();
        let sql;

        if (checkbox.checked)
        {
            sql = `UPDATE article SET etat_stock = 1 WHERE id = ${product_id} AND num_commande = ${order_id}`;
            xhr.send(JSON.stringify({sql: sql}));

            xhr = makeRequest();
            sql = `UPDATE produit SET stock = stock - ${product_quantity} WHERE id = ${product_id}`;
            xhr.send(JSON.stringify({sql: sql}));
        } 
        else
        {     
            sql = `UPDATE article SET etat_stock = 0 WHERE id = ${product_id} AND num_commande = ${order_id}`;
            xhr.send(JSON.stringify({sql: sql}));
        }

        // 更新订单状态
        xhr = makeRequest();
        sql = `UPDATE commande SET etat_commande = 2, date_traitement = '${date}' WHERE num_commande = ${order_id}`;
        xhr.send(JSON.stringify({sql: sql}));
    });

    window.location.reload();
}

function makeRequest()
{
    const xhr = new XMLHttpRequest();
    const url = "db_query.php";

    xhr.onreadystatechange = function()
    {
      if (this.readyState == 4 && this.status == 200)
      {
        const results = JSON.parse(this.responseText);
        // 可在此添加请求成功/失败的处理逻辑,比如错误提示
      }
    };
    
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json");

    return xhr;
}

额外注意事项

  • 防范SQL注入:当前代码直接将变量拼入SQL语句,存在严重安全风险,建议在db_query.php中使用PDO预处理语句实现参数化查询。
  • 规范使用data属性:通过dataset访问data属性,会自动处理驼峰命名转换(如data-product-quantity对应dataset.productQuantity),比getAttribute更简洁可靠。

内容的提问来源于stack exchange,提问作者ŨNKNŐWŇ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:22:04