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

如何将弹窗选中的产品数据提取并展示到表格中?

问题描述

我需要实现点击表格中的「Add Product」按钮弹出选择窗口,选中产品后将其名称和详情展示到主表格中,数据来自数据库。

现有界面情况:

  • 主表格包含Component、Product、Details、Remove四列,初始时Product列为空,Details列显示Add Product按钮,Remove按钮隐藏
  • 弹窗中列出数据库中的CPU产品,每行包含产品名称、详情和Add按钮
  • 期望选中产品后,主表格的Product列显示选中产品名称,Details列显示完整详情,同时显示Remove按钮

现有代码问题分析

当前代码存在几个关键问题:

  1. 弹窗通过window.open创建新窗口,导致父页面的selectProduct函数无法被新窗口调用,会触发函数未定义错误
  2. AJAX请求返回完整的CPU数据对象,但代码错误尝试访问不存在的response.details字段
  3. 隐藏弹窗的逻辑错误,新窗口不是页面中的productPopup元素,无法通过该元素控制显示状态

修正方案

改用模态弹窗替代新开窗口,同时修复数据处理逻辑,以下是完整可运行的代码:

主页面代码

<table id="data_table">
    <thead>
        <tr>
            <th>Component</th>
            <th class="status-column1">Product</th>
            <th class="status-column">Details</th>
            <th>Remove</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="no-border-right">Processor</td>
            <td class="no-border-right no-border-left" id="selectedProductCell"></td>
            <td class="no-border-right no-border-left" id="selectedProductDetailCell">
                <button onclick='openPopup()' class="addButton"><i class="fa fa-plus"></i>Add Product</button>
            </td>
            <td class="no-border-left">
                <button class="removeButton" style="display: none;">Remove</button>
            </td>
        </tr>
    </tbody>
</table>

<!-- 模态弹窗容器 -->
<div id="productPopup" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
    <div style="background: white; margin: 50px auto; padding: 20px; width: 80%; max-width: 700px; border-radius: 8px;">
        <h2 style="text-align: center; margin-top: 0;">Select a CPU Product</h2>
        <table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
            <thead>
                <tr>
                    <th style="border-bottom: 1px solid #ccc; padding: 8px;">Product Name</th>
                    <th style="border-bottom: 1px solid #ccc; padding: 8px;">Details</th>
                    <th style="border-bottom: 1px solid #ccc; padding: 8px;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                // 从数据库获取CPU产品数据
                $query = "SELECT * FROM cpu_db";
                $result = mysqli_query($connection, $query);
                while ($row = mysqli_fetch_assoc($result)) {
                    $details = $row['brand'] . ' ' . $row['c_speed'] . ' ' . $row['cores'] . ' ' . $row['mem_supp'];
                ?>
                <tr>
                    <td style="border-bottom: 1px solid #eee; padding: 8px;"><?php echo $row['name']; ?></td>
                    <td style="border-bottom: 1px solid #eee; padding: 8px;"><?php echo $details; ?></td>
                    <td style="border-bottom: 1px solid #eee; padding: 8px; text-align: center;">
                        <button onclick='selectProduct("<?php echo $row['name']; ?>")'>Add</button>
                    </td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <button onclick='closePopup()' style="margin-top: 20px; padding: 8px 16px; float: right;">Close</button>
        <div style="clear: both;"></div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // 打开模态弹窗
    function openPopup() {
        document.getElementById('productPopup').style.display = 'block';
    }

    // 关闭模态弹窗
    function closePopup() {
        document.getElementById('productPopup').style.display = 'none';
    }

    // 选中产品后更新主表格
    function selectProduct(productName) {
        closePopup();
        
        // 更新Product列内容
        document.getElementById('selectedProductCell').textContent = productName;
        
        // 显示Remove按钮
        document.querySelector('.removeButton').style.display = 'inline';

        // 发送AJAX请求获取完整产品详情
        $.ajax({
            type: "GET",
            url: "view_cpu_details.php",
            data: { product_name: productName },
            dataType: "json",
            success: function(response) {
                // 拼接详情文本
                const detailsText = `${response.brand} ${response.c_speed} ${response.cores} ${response.mem_supp}`;
                // 更新Details列,替换Add按钮为详情文本
                document.getElementById('selectedProductDetailCell').innerHTML = detailsText;
            },
            error: function(error) {
                console.error("获取数据失败:", error);
                document.getElementById('selectedProductDetailCell').innerHTML = "获取详情失败";
            }
        });
    }

    // Remove按钮点击事件:恢复初始状态
    document.querySelector('.removeButton').addEventListener('click', function() {
        document.getElementById('selectedProductCell').textContent = '';
        const detailsCell = document.getElementById('selectedProductDetailCell');
        detailsCell.innerHTML = '<button onclick="openPopup()" class="addButton"><i class="fa fa-plus"></i>Add Product</button>';
        this.style.display = 'none';
    });
</script>

view_cpu_details.php 代码

<?php
include 'connection.php';

header('Content-Type: application/json');

if (isset($_GET['product_name'])) {
    $product_name = $_GET['product_name'];

    $query = "SELECT * FROM cpu_db WHERE name = ?";
    $stmt = mysqli_prepare($connection, $query);
    mysqli_stmt_bind_param($stmt, "s", $product_name);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if ($result && mysqli_num_rows($result) > 0) {
        $cpu_details = mysqli_fetch_assoc($result);
        echo json_encode($cpu_details);
    } else {
        echo json_encode(['error' => 'CPU details not found.']);
    }

    mysqli_stmt_close($stmt);
} else {
    echo json_encode(['error' => 'Product name not provided.']);
}
?>

关键修正说明
  1. 模态弹窗替代新窗口:避免跨窗口函数调用问题,弹窗直接在当前页面展示,交互更流畅
  2. 简化数据传递:只传递产品名称,详情通过AJAX获取后拼接,减少数据冗余
  3. 修复AJAX解析:指定dataType: "json"确保正确解析响应数据
  4. 添加重置逻辑:点击Remove按钮可恢复表格初始状态
  5. 原生PHP生成弹窗列表:无需将数据转成JSON给JS循环,代码更简洁高效

内容的提问来源于stack exchange,提问作者needsHelp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:09:50