2013-10-30 23 views
0

我试图在Shopify中对购物车中的产品类型进行一些计算。这需要2个相关的getJSON调用。下面是我目前的代码,显然它有一些问题,我不知道克服它们的最佳方法。我不想关闭异步,因为这看起来像是一种拙劣的方式。使用Shopify和JQuery在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; 
    }); 
}); 

回答

相关问题