Magento:获取AJAX响应中所有更新的购物车商品数据

时间:2013-12-19 13:43:33

标签: ajax magento magento-1.7 cart

我的购物车看起来像是弹出窗口:

enter image description here

我正在通过AJAX Call一次更新购物车中的多个可配置项目。

但是我无法将所有项目数据恢复为AJAX响应。

我只得到第一项itemPrice和rowTotal。对于剩余项目,itemPrice和rowTotal设置为0。

代码:

public function updateItemOptionsAction()
{
    $cartData = $this->getRequest()->getParam('cart');
    Mage::log($cartData);
    if (is_array($cartData)) {
        $result = array();
        $result['data'] = array();
        foreach ($cartData as $index => $data) {
            $cart   = $this->_getCart();
            $params = $data;
            $id = (int)$data['id'];

            if (!isset($params['options'])) {
                $params['options'] = array();
            }
            $result['data'][$index] = array();
            $oldQty = null;
            $kitType = $params['efk_kType'];
            $params['super_attribute'] = array($data['sAttr']=>$kitType);
            unset($params['sAttr']);
            $stock = null;
            try {
                if (isset($params['qty'])) {
                    $product = Mage::getModel("catalog/product")->load($params['product']);
                    $childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
                    foreach($childProducts as $cProd){
                        if($cProd->getKitType() == $kitType){
                            $stock = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($cProd)->getQty());
                        }
                    }
                    if(intval($params['qty']) > $stock){
                        $oldQty = intval($params['qty']);
                        $params['qty'] = $stock;
                        $result['data'][$index]['revised'] = true;
                    }

                    $filter = new Zend_Filter_LocalizedToNormalized(
                        array('locale' => Mage::app()->getLocale()->getLocaleCode())
                    );
                    $params['qty'] = $filter->filter($params['qty']);
                }

                $quoteItem = Mage::getSingleton('checkout/cart')->getQuote()->getItemById($id);
                if (!$quoteItem) {
                    Mage::throwException($this->__('Quote item is not found.'));
                }

                //Its going to infinity loop duwe to Varien Object need to check later
                //$item = $cart->updateItem($id, new Varien_Object($params));
                $item = Mage::getSingleton('checkout/cart')->updateItem($id, $params);

                if (is_string($item)) {
                    Mage::throwException($item);
                }
                if ($item->getHasError()) {
                    Mage::throwException($item->getMessage());
                }
                Mage::log('hi2');

                $related = $params['related_product'];
                if (!empty($related)) {
                    Mage::getSingleton('checkout/cart')->addProductsByIds(explode(',', $related));
                }

                Mage::getSingleton('checkout/cart')->save();
                Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

                Mage::dispatchEvent('checkout_cart_update_item_complete',
                    array('item' => $item, 'request' => $this->getRequest(), 'response' => $this->getResponse())
                );
                $cart->getQuote()->setTotalsCollectedFlag(false);
                Mage::getSingleton('checkout/cart')->init();

                if (!Mage::getSingleton('checkout/session')->getNoCartRedirect(true)) {
                    if (!Mage::getSingleton('checkout/cart')->getQuote()->getHasError()) {
                        Mage::log('hi4');
                        $result['success'] = true;
                        if($oldQty > $item->getQty()){
                            $message = $this->__('%s has been revised due to stock limitations. You may proceed with the order for the revised quantity.', Mage::helper('core')->escapeHtml($item->getProduct()->getName()));
                        }else{
                            $message = $this->__('%s was updated in your shopping cart.', Mage::helper('core')->escapeHtml($item->getProduct()->getName()));
                        }
                        $result['data'][$index]['message'] = $message;
                        $result['data'][$index]['itemId'] = $item->getId();
                        $result['data'][$index]['itemPrice'] = Mage::helper('checkout')->formatPrice($item->getCalculationPrice());
                        $result['data'][$index]['qty'] = $item->getQty();
                        $result['data'][$index]['rowTotal'] = Mage::helper('checkout')->formatPrice($item->getRowTotal());
                    }
                }

            } catch (Mage_Core_Exception $e) {
                $result['success'] = false;
                $result['data'][$index]['success'] = 'qty';
                $result['data'][$index]['message'] = $e->getMessage();
            } catch (Exception $e) {
                $result['success'] = false;
                $result['data'][$index]['message'] = $e->getMessage();
                $result['data'][$index]['secondMessage'] = $this->__('Cannot update the item.');
            }
        }



        $result['data']['grandTotal'] = Mage::helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal());
        $result['data']['totalItems'] = Mage::getSingleton('checkout/cart')->getSummaryQty();
        $totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
        $result['data']['subTotal'] = Mage::helper('checkout')->formatPrice($totals['subtotal']->getValue());
        if(isset($totals['discount']) && $totals['discount']->getValue()){
            $result['data']['discount'] = Mage::helper('checkout')->formatPrice($totals['discount']->getValue());
        }else{
            $result['data']['discount'] = Mage::helper('checkout')->formatPrice(0);
        }
    }
    $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}

AJAX响应我正在

{
    "data": {
        "1187": {
            "success": true,
            "message": "THREE PHASE SOLID STATE RELAY WITH ZVS was updated in your shopping cart.",
            "itemId": "1191",
            "itemPrice": "<span class=\"price\">20b9  3,799</span>",
            "qty": 1,
            "rowTotal": "<span class=\"price\">20b9  3,799</span>",
            "forLoop": "yes"
        },
        "1189": {
            "success": true,
            "message": "AUTO INTENSITY CONTROL OF STREET LIGHTS was updated in your shopping cart.",
            "itemId": "1193",
            "itemPrice": "<span class=\"price\">20b9  0</span>",
            "qty": 1,
            "rowTotal": "<span class=\"price\">20b9  0</span>",
            "forLoop": "yes"
        },
        "grandTotal": "<span class=\"price\">20b9  8,798</span>",
        "totalItems": 2,
        "subTotal": "<span class=\"price\">20b9  8,798</span>",
        "discount": "<span class=\"price\">20b9  0</span>"
    }
}

我得到itemPrice和第二项的rowTotal为0.每次我只获得第一项的正确值。如果我一次更新5个项目(例如),那么我得到的是第1项的正确值,对于我正在获得0的remianing项目。

如果我在获得AJAX响应后刷新购物车,那么它会正确显示所有商品的itemPrice和rowTotal更新值。

注意:20b9是印度卢比符号的HEX代码

请指出我错在哪里。

提前致谢。

1 个答案:

答案 0 :(得分:1)

你的工作太难了...尝试更新控制器服务器端的项目,保存当前的报价...然后只需要一个加载当前.phtml的控制器方法并返回html作为购物车块的json,并用新的替换整个购物车html块(div)。

在控制器方法结束时

$this->getResponse()->setBody( json_encode(
array("html" => 
            Mage::app()->getLayout()->createBlock('checkout/[[whatevertag_is_to_cart_div phtml block]]')->toHtml()
     )
);
相关问题