【问题标题】:How to push data to array using ajax如何使用ajax将数据推送到数组
【发布时间】:2025-12-08 08:15:02
【问题描述】:

我有一个页面列出产品 - 每个产品都有一个添加到购物车按钮。使用按钮中的数据属性,我需要将 offerId 字符串推送到现有数组中。将多个产品添加到购物车后的预期结果是返回一个包含所有 offerId 的数组。目前,如果我 print_r 的 offerIdArray,它只显示最新按钮的 offerId。

想法?

$(document).ready(function () {
    $(".addtocart button").click(function () {
        var offerIdArray = [];
        var offerId = $(this).attr("data-offerId");
        $.post("controller/create-cart.php", {
            offerIdArray: offerIdArray.push(offerId)
        },
        function (data) {
            $('body').append(data);
        });
    });
});

编辑:下面是我的工作代码 - 感谢@brroshan。我还必须先将 offerId 推送到 offerIdArray,然后才能通过 post 发送数组。

$(document).ready(function () { 
    offerIdArray = [];                                
    $(".addtocart button").click(function () {                    
        var offerId = $(this).attr("data-offerId"); 
        offerIdArray.push(offerId);                    
        $.post("controller/create-cart.php",
            {                                
                offerIdArray: offerIdArray
            },
            function (data) {
                $('body').append(data);
            }
        );
    });
});

【问题讨论】:

  • 能否显示$(this).attr("data-offerId")的返回值;

标签: jquery arrays ajax post


【解决方案1】:

问题是每次单击".addtocart button" 时都会创建一个新数组。只需在点击处理程序之外声明您的数组,它应该可以工作。

$(document).ready(function () {
      var offerIdArray = [];       // <--
      $(".addtocart button").click(function () {

        var offerId = $(this).attr("data-offerId");

        $.post("controller/create-cart.php", {
            offerIdArray: offerIdArray.push(offerId)
        },
        function (data) {
            $('body').append(data);
        });
   });
});

【讨论】:

    【解决方案2】:

    将 offerIdArray 移到函数之外。现在它是一个局部变量。因此,您每次调用该函数时都在重新创建它。你需要一个全局变量。我希望这会有所帮助。

    【讨论】: