使用Shopify和JQuery在getJSON调用内外使用变量?

时间:2013-10-30 17:21:23

标签: javascript jquery json shopify

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

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;  
  });
});   

1 个答案:

答案 0 :(得分:2)

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