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

基于PHP+JS实现条码输入后动态生成表格行的技术求助

入门级实现方案:PHP+原生JS完成条码查询与表格行新增

一、HTML基础结构

先搭好初始表格,表头按你需要的商品字段设置(比如条码、名称、价格、库存),第二行放条码输入框,其余单元格留空:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>条码录入</title>
    <style>
        table { border-collapse: collapse; width: 80%; margin: 20px auto; }
        th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
        input[type="text"] { padding: 6px; width: 90%; }
    </style>
</head>
<body>
    <table id="productTable">
        <thead>
            <tr>
                <th>条码</th>
                <th>商品名称</th>
                <th>单价</th>
                <th>库存</th>
            </tr>
        </thead>
        <tbody>
            <!-- 初始行 -->
            <tr>
                <td><input type="text" class="barcodeInput" placeholder="输入条码回车查询"></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </tbody>
    </table>

    <script>
        // JS逻辑写在这里
    </script>
</body>
</html>

二、PHP后端接口(get_product.php)

这个文件负责接收前端传的条码,从MySQL查商品数据,返回JSON格式结果。注意用预处理语句防SQL注入:

<?php
// 数据库配置,替换成你的实际信息
$host = 'localhost';
$dbname = '你的数据库名';
$username = '数据库用户名';
$password = '数据库密码';

// 连接数据库
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die(json_encode(['success' => false, 'msg' => '数据库连接失败']));
}

// 获取前端传来的条码
$barcode = $_GET['barcode'] ?? '';
if(empty($barcode)) {
    echo json_encode(['success' => false, 'msg' => '条码不能为空']);
    exit;
}

// 查询商品数据(假设商品表名为products,字段对应barcode、name、price、stock)
$stmt = $pdo->prepare("SELECT name, price, stock FROM products WHERE barcode = ?");
$stmt->execute([$barcode]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if($product) {
    echo json_encode([
        'success' => true,
        'data' => [
            'name' => $product['name'],
            'price' => $product['price'],
            'stock' => $product['stock']
        ]
    ]);
} else {
    echo json_encode(['success' => false, 'msg' => '未找到该商品']);
}
?>

三、原生JS实现AJAX与表格操作

在HTML的script标签里写逻辑,监听输入框的回车事件,发AJAX请求更新当前行,然后新增一行:

// 获取表格tbody元素
const tbody = document.querySelector('#productTable tbody');

// 用事件委托给所有条码输入框绑定回车事件
tbody.addEventListener('keydown', function(e) {
    if(e.key === 'Enter' && e.target.classList.contains('barcodeInput')) {
        const barcode = e.target.value.trim();
        if(!barcode) return;

        const currentRow = e.target.parentElement.parentElement; // 当前输入框所在行
        const cells = currentRow.querySelectorAll('td'); // 当前行的所有单元格

        // 发送AJAX请求
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `get_product.php?barcode=${encodeURIComponent(barcode)}`, true);
        xhr.onload = function() {
            if(xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if(response.success) {
                        // 更新当前行的商品信息
                        cells[1].textContent = response.data.name;
                        cells[2].textContent = response.data.price;
                        cells[3].textContent = response.data.stock;

                        // 新增一行相同结构的空行
                        const newRow = document.createElement('tr');
                        newRow.innerHTML = `
                            <td><input type="text" class="barcodeInput" placeholder="输入条码回车查询"></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        `;
                        tbody.appendChild(newRow);

                        // 自动聚焦到新行的输入框
                        newRow.querySelector('.barcodeInput').focus();
                    } else {
                        alert(response.msg);
                    }
                } catch(err) {
                    alert('数据解析失败');
                }
            } else {
                alert('请求失败,请稍后重试');
            }
        };
        xhr.onerror = function() {
            alert('网络错误');
        };
        xhr.send();
    }
});

注意事项

  • 替换PHP里的数据库配置信息,确保商品表字段和代码里的对应一致
  • 测试时要把HTML和PHP文件放在同一服务器环境下(比如XAMPP、WAMP),避免跨域问题
  • 可以根据实际需求调整表格字段数量、样式或AJAX请求方式(比如POST)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:30:53