简体   繁体   English

当使用jQuery完成AJAX调用时的回调

[英]Callback when AJAX calls are done using jQuery when

I am having trouble making the callback work correctly. 我无法使回调正常工作。 Here is what I am trying to achieve: I have 2 items that I want to add to cart so I make 2 asynchronous POST requests. 这是我要实现的目标:我有2个项目要添加到购物车,所以我发出2个异步POST请求。 Once those two POST requests are complete, then I want to update the partial view of the cart. 完成这两个POST请求后,我想更新购物车的部分视图。 The issue is that it seems like only 1 item gets added to cart. 问题是似乎只有1个项目被添加到购物车。 When I debug it, then 2 of the items gets added. 当我调试它时,然后添加其中2个项目。 Any suggestion or help would be great. 任何建议或帮助都会很棒。 Thanks in advance! 提前致谢!

here is my code: 这是我的代码:

var cart = []

function AddToCart(input) {
  return $.ajax({
    method: 'POST',
    url: '/cart/add.js',
    data: input,
    dataType: 'json'
  })
  .done(function(data) {
    return data;
  });
}  

$("#addToCart").click(function() {
  $('#capsContainer input:checked').each(function() {
    var cartItem = {
      id: $(this).val(),
      quantity: 1
    }

    cart.push(cartItem);
  });

  var test1 = AddToCart(cart[0]);
  var test2 = AddToCart(cart[1]);

  $.when.apply(test1, test2).done(function() {
        $.getJSON('/cart.js', function(data) {
        $('.cart-item-count').text(data.item_count);
        $('.cart-item-price').html(formatMoney(data.total_price));      
        ShowCart();
    });
  })
});

Part of the issue is that your using ajax requests which could occur either before or after the code happens to handle those executions. 问题的一部分是您使用的ajax请求可能发生在代码处理这些执行之前或之后。 Since they are async, its possible that they could fire/return before any other code runs on the page depending on how your browser's Javascript parser decides to execute the code. 由于它们是异步的,因此有可能在页面上运行任何其他代码之前触发/返回,这取决于浏览器的Javascript解析器决定执行代码的方式。 Rather than attempting to use Callbacks on asynchronous ajax requests, you can control the entire interaction by using a small 600 byte library called ajaxq.js 您可以尝试使用名为ajaxq.js的 600字节小型库来控制整个交互,而不必尝试对异步ajax请求使用回调。

ajaxq.js essentially works just like jQuery's $.post() method, only you can also specify multiple queues by name to execute asyncronously, and attach a callback to them or whatever. ajaxq.js本质上与jQuery的$.post()方法一样,仅您还可以按名称指定多个队列以异步执行,并将回调函数附加到它们上。

Here's a quick example of how you could setup your Ajax Cart Preview using this library. 这是一个简单的示例,说明如何使用此库设置Ajax Cart Preview。

/* queue up an AJAX request */
$.postq("set_data", "add_items.php", {"itemID": someItemID, "customerID": customerID },
  function(result1) {


  /* perform new request at the end of first request */

  $.postq("get_data", "get_items.php", { "id": customerID }, 
      function(result2) {

    /* add in code to perform at the end of the second ajax POST request */

  }); // end of request 2

}); // end of request 1

Here's your example using the ajaxq.js library: 这是使用ajaxq.js库的示例:

function AddToCart(input) {
   $.postq("add_item", "/cart/add/js", input, function(result) {
        preview_items();
    }, "json");

}  

function preview_items() {
 $.getJSON('/cart.js', function(data) {
        $('.cart-item-count').text(data.item_count);
        $('.cart-item-price').html(formatMoney(data.total_price));      
        ShowCart();
}


$(document).ready(function() { 
  $("#addToCart").on("click" function() {
    $('#capsContainer input:checked').each(function(elem) {
      var cartItem = {
        id: $(this).val(),
       quantity: 1
      }

      cart.push(cartItem);
    });

    var test1 = AddToCart(cart[0]);
    var test2 = AddToCart(cart[1]);

  });

Your AddToCart method already returns a deferred object. 您的AddToCart方法已经返回了延迟的对象。 You are calling .done method twice. 您正在两次调用.done方法。

I guess your code should look like this. 我猜你的代码应该看起来像这样。

var cart = []

function AddToCart(input) {
  return $.ajax({
    method: 'POST',
    url: '/cart/add.js',
    data: input,
    dataType: 'json'
  });
}  

$("#addToCart").click(function() {
  $('#capsContainer input:checked').each(function() {
    var cartItem = {
      id: $(this).val(),
      quantity: 1
    }

    cart.push(cartItem);
  });

  var test1 = AddToCart(cart[0]);
  var test2 = AddToCart(cart[1]);

  $.when(test1, test2).done(function() {
        $.getJSON('/cart.js', function(data) {
            $('.cart-item-count').text(data.item_count);
            $('.cart-item-price').html(formatMoney(data.total_price));      
            ShowCart();
        });
      })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM