weixin_33713707 2016-03-10 09:55 采纳率: 0%
浏览 8

具有多个提交的AJAX

I currently have a 'Add to Cart' button which submits product data from an array and posts the data using AJAX.

Currently on submit only one of the three products are been send to the cart.

I was told to use .then function after each AJAX post but I'm unsure how to tie this in with the for() function and the array.

Any and all help would be very much appreciated! Thank you.

function addtocart() {
  var products = [{
    'id': 32,
    'qty': 2
  }, {
    'id': 33,
    'qty': 1
  }, {
    'id': 34,
    'qty': 5
  }];

  $('.submit').on('click', function(e) {
    e.preventDefault();
    for (var j = 0; j < products.length; j++) {
      jQuery.ajax({
        type: 'POST',
        url: 'XXX/?post_type=product&add-to-cart=' + products[j].id + '&quantity=' + products[j].qty
      });
    }
  });
}
<div class="addtocart">
    <button class="submit">Add to Cart</button>
</div>

Update:

function addtocart() {
  var products = [{'product_id':32,'quantity':2},{'product_id':33,'quantity':1},{'product_id':34,'quantity':5}];
  $('.submit').on('click', function(e){
    e.preventDefault();
    $.ajax(
      { 
        type:'POST',
        url:'XXX/?post_type=product&add-to-cart', 
        data:JSON.stringify(products) 
       }
     );
     console.log(JSON.stringify(products));
  });
}
addtocart();

Network Snapshot
Console Log Snapshot

I was told to do something like this, but I can't add an ID without it been within a for()

url: 'XXX/?post_type=product&add-to-cart='+IDHERE
  • 写回答

0条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 Qt Vs2017使用Charts异常
      • ¥15 将位图选入内存DC失败,但没有出错信息
      • ¥20 如何从 .html url 启动/激活 .py 文件(sql debug)
      • ¥15 c#调用soap出错,soapui中可以
      • ¥100 CBIS-DDSM kaggle 资料处理
      • ¥30 python 在 excel 用 OpenPyXL 怎么实现以下代码
      • ¥15 pywinauto 无法捕获到元素
      • ¥15 ARfoundation (可能由于没打开摄像头的)黑屏问题
      • ¥15 C++类模板继承模板本身,有偿
      • ¥15 pycharm打包项目包含mp3文件,运行exe程序后mp3文件没有执行。