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

点击按钮通过Ajax向PHP传数据并实现多商品加入购物车

解决多商品添加至购物车的问题

嘿,我来帮你搞定这个购物车只能添加单个商品、旧商品被覆盖的问题!咱们先捋清楚问题根源,再一步步修改代码:

问题根源

  1. 重复的ID导致获取错误数据:你在foreach循环里给每个商品的隐藏输入框和按钮都用了相同的id(比如product_id、add_to_cart),但ID在页面中是唯一的,所以JS只能获取到第一个商品的信息。
  2. 覆盖式更新购物车:每次添加成功后用html()方法直接替换购物车容器的内容,旧的商品自然就被新的覆盖掉了。

第一步:修复HTML结构(解决重复ID问题)

把循环里所有重复的id改成class,给每个商品包裹一个容器方便JS定位,同时把按钮的type="submit"改成type="button"(避免触发默认的表单提交行为):

<?php foreach ($products as $product):?>
<?php if($product['kateg'] == "men"):?>
<!-- 新增商品容器,用于定位当前商品的所有信息 -->
<div class="product-item">
  <h5 style="color: #0669b4; min-height: 70px;"><?php echo $product['dasax']?></h5>
  <p style="text-align: left; text-decoration: overline">Old price: <strong><span style="text-decoration: line-through"><?php echo round($product['fasi1'], 2)?> GEL</span></strong><br></p>
  <p style="text-align: left">New Price: <strong><?php echo round($product['fasi2'], 2)?> GEL</strong><br></p>
  <!-- 把id替换成class,允许重复使用 -->
  <input type="hidden" value="<?php echo $product['id']?>" class="product_id">
  <input type="hidden" value="<?php echo $product['dasax']?>" class="product_name">
  <input type="hidden" value="<?php echo $product['fasi2']?>" class="product_price">
  <!-- 按钮id改成class,type改为button -->
  <button class="btn btn-primary add_to_cart_btn" type="button">Add</button>
</div>
<?php endif;?>
<?php endforeach;?>

第二步:修改JS逻辑(实现追加式添加)

调整事件绑定方式,正确获取当前点击商品的信息,并用append()代替html()实现追加商品,而不是覆盖:

$(document).ready(function () {
  // 绑定class的点击事件,用on确保动态生成的按钮也能生效(这里虽然是静态生成,但这个写法更通用)
  $(document).on('click', '.add_to_cart_btn', function () {
    // 找到当前点击按钮所在的商品容器,再获取该容器内的商品信息
    var $currentItem = $(this).closest('.product-item');
    var product_id = $currentItem.find(".product_id").val();
    var product_name = $currentItem.find(".product_name").val();
    var product_price = $currentItem.find(".product_price").val();

    $.ajax({
      url: "/uketesi/index",
      method: "POST",
      dataType: "json",
      data: {
        product_id: product_id,
        product_name: product_name,
        product_price: product_price,
      },
      success:function (data) {
        alert("produqti warmatebit daemata");
        // 你的购物车容器(注意这里的id看起来有编码乱码,建议检查修正)
        var $cartContainer = $("#醿欋儛醿氠儛醿椺儛");
        
        // 检查购物车是否已经存在表格,如果没有则先创建完整的表格结构(包含表头)
        if ($cartContainer.find('#example2').length === 0) {
          var tableStructure = `
            <table id="example2" class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th>醿撫儛醿♂儛醿償醿氠償醿戓儛</th>
                  <th>醿め儛醿♂儤</th>
                  <th>醿樶儞醿斸儨醿⑨儤醿め儤醿欋儛醿⑨儩醿犪儤</th>
                </tr>
              </thead>
              <tbody></tbody> <!-- 新增tbody,专门用来追加商品行 -->
            </table>
          `;
          $cartContainer.html(tableStructure);
        }

        // 生成新商品的行,并追加到表格的tbody中
        var newProductRow = `
          <tr>
            <td>${product_name}</td>
            <td>${product_price}</td>
            <td>${product_id}</td>
          </tr>
        `;
        $cartContainer.find('#example2 tbody').append(newProductRow);
      }
    });
  });
});

可选优化建议

  • 重复商品判断:可以在前端或者后端添加逻辑,如果购物车中已经存在该商品,就更新数量而不是重复添加一行
  • 修复乱码表头:你购物车的表头文字看起来是编码乱码(比如“醿撫儛醿♂儛醿償醿氠償醿戓儛”),建议检查页面编码,替换成正常的文字(比如“商品名称”、“价格”、“商品ID”)
  • 添加删除功能:可以给每个购物车商品行添加删除按钮,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:30:10