0

我正在尝试对 Shopify 中购物车中的产品类型进行一些计算。这需要 2 个相关的 getJSON 调用。下面是我目前拥有的代码,显然它有一些问题,我不知道克服它们的最佳方法。我不想关闭异步,因为这似乎是一种 hacky 方式。

var smallCount, mediumCount, largeCount; 

$(document).ready(function()
{
  $.getJSON('/cart.js', function(cart) //Gets all the items in a cart.
  {

    smallCount = 0; mediumCount = 0; largeCount = 0;

    //Go through each item in the cart.
    for(var i = 0; i < cart.items.length; i++)
    {   
            //For each item we're going to grab the json info
            //Specifically looking for the product type
        $.getJSON('/products/'+cart.items[i].handle+'.js', function(product) { 
            if(product.type == "Small")
            { smallCount += cart.items[i].quantity; } //These don't work
            else if (product.type == "Medium")
            { mediumCount += cart.items[i].quantity; } //These don't work
            else if (product.type == "Large")
            { largeCount += cart.items[i].quantity; } //These don't work
        }); 
    }

    //Here or below I'd like to do some analysis on the product types in the cart.
    //I want to get all of the counts and then do some work with them.
    mathHappening = smallCount + mediumCount + largeCount;  
  });
});   
4

1 回答 1

2

请查看http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/。可能这就是你想要使用的。

于 2013-10-30T17:52:40.237 回答