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

使用PHP与Ajax从MySQL取数填充动态输入时数据错位问题求助

问题根因

核心是JavaScript异步回调的闭包变量共享问题:你声明的全局变量i会在每次点击新增按钮时自增,Ajax请求是异步执行的,等到请求成功触发回调函数时,i已经被后续操作更新为更大的数值,所以回调里拿到的i不是绑定下拉框change事件时的数值,自然就会把价格填充到后续生成的输入框中。

另外你还存在两个隐藏问题:

  • 初始加载的第一组表单的下拉框没有绑定change事件,选择后不会触发价格查询
  • PHP端的预处理SQL写法错误,直接拼接用户输入参数存在SQL注入风险

修复方案

1. 优化jQuery事件绑定逻辑(推荐用相对DOM查找方案,无需维护动态id,稳定性更高)

给下拉框和价格输入框新增类名标识,通过DOM层级相对查找对应输入框,完全不需要依赖动态id和变量i,从根源避免变量共享问题,修改后的代码如下:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  // 绑定初始第一组表单的查询事件
  bindPriceQuery($('#itemname'));

  var i = 1;
  $('#add').click(function(){
    i++;
    // 新增表单节点,给下拉框加item-select类,价格输入框加price-input类
    const newFormGroup = $(`
    <div class="form-group">
      <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
        <div class="box">
          <header>
            <h5>تفاصيل الطلب</h5>
          </header>
          <div class="body">
            <div class="form-group">
              <label class="control-label col-lg-2">الصنف</label>
              <div class="col-lg-10">
                <select name="itemname[]" class="form-control item-select">
                  <option disabled selected>اختر الصنف</option>
                  <?php echo getValues($pdo); ?>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-lg-2">السعر</label>
              <div class="col-lg-10">
                <input type="text" name="price[]" placeholder="-" readonly class="form-control price-input">
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-lg-2">الكمية</label>
              <div class="col-lg-10">
                <input class="form-control" type="text" name="quantity[]" value="0" min="1">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    `);
    $('#append').append(newFormGroup);
    // 给新增的下拉框绑定查询事件
    bindPriceQuery(newFormGroup.find('.item-select'));
  });

  // 公用的价格查询绑定方法
  function bindPriceQuery($select) {
    $select.change(function(){
      const $currentSelect = $(this);
      // 相对查找当前组对应的价格输入框
      const $targetPriceInput = $currentSelect.closest('.box').find('.price-input');
      const code = $currentSelect.val();
      $.ajax({
        type: 'POST',
        url: 'pages/GetPrice.php',
        data: {code: code},
        success: function(data){
          $targetPriceInput.val(data);
        },
        error: function (jqXHR, textStatus, errorThrown){
          alert(errorThrown);
        }
      });
    });
  }
});
</script>

2. 修复PHP端SQL注入风险

你之前的预处理SQL写法没有起到防注入作用,修改为参数绑定写法:

<?php
    require 'DBConnection.php';
    $code = '';
    if(isset($_POST["code"])){
        $id = $_POST["code"];
        // 用参数绑定替换字符串拼接,避免SQL注入
        $get_c = $pdo->prepare("SELECT * FROM all_menu WHERE `item_name` = ?");
        $get_c->execute([$id]);
        while ($row = $get_c->fetch()) {
            $code .= $row['price'];
        }
        echo $code;
    }
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:45:03