Hello All我使用ajax方法为可配置产品添加多个关联产品。我使用了下面的代码,我的代码运行良好,但无法隐藏加载程序并在成功后提醒消息。
的Js代码
<script type="text/javascript">
var productAddToCartForm = new VarienForm('product_addtocart_form_ext');
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
//Start of our new ajax code
if(!url){
url = jQuery('#product_addtocart_form_ext').attr('action');
}
var data = jQuery('#product_addtocart_form_ext').serialize();
data += '&isAjax=1';
jQuery('#ajax_loader').show();
try {
jQuery.ajax({
url: url,
dataType: 'json',
type : 'post',
data: data,
success: function(data){
alert('successfully added');
jQuery('#ajax_loader').hide();
alert('successfully added');
}
});
} catch (e) {
}
//End of our new ajax code
this.form.action = oldUrl;
if (e) {
throw e;
}
}
}.bind(productAddToCartForm);
</script>
Php Code
public function addmultipleAction() {
$productIds = $this->getRequest()->getParam('products');
if (!is_array($productIds)) {
$this->_goBack();
return;
}
$params = $this->getRequest()->getParams();
if ($params['isAjax'] == 1) {
$response = array();
foreach ($params['products'] as $p) {
$key = 'qty' . $p;
if (strlen(trim($params[$key]))) {
$response[] = $p;
}
}
$productIds = $response;
foreach ($productIds as $productId) {
try {
$qty = $this->getRequest()->getParam('qty' . $productId, 0);
$cart = $this->_getCart();
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($productId)
->setConfiguredAttributes($this->getRequest()->getParam('super_attribute'))
->setGroupedProducts($this->getRequest()->getParam('super_group', array()));
$eventArgs = array(
'product' => $product,
'qty' => $qty,
'additional_ids' => array(),
'request' => $this->getRequest(),
'response' => $this->getResponse(),
);
$params['qty'] = $qty;
Mage::dispatchEvent('checkout_cart_before_add', $eventArgs);
$cart->addProduct($product, $params);
Mage::dispatchEvent('checkout_cart_after_add', $eventArgs);
//$cart->save();
// Mage::dispatchEvent('checkout_cart_add_product', array('product'=>$product));
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
$response['status'] = 'SUCCESS';
$response['message'] = $message;
Mage::getSingleton('checkout/session')->addSuccess($message);
} catch (Mage_Core_Exception $e) {
if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
Mage::getSingleton('checkout/session')->addNotice($product->getName()
. ': ' . $e->getMessage());
} else {
Mage::getSingleton('checkout/session')->addError($product->getName() .
': ' . $e->getMessage());
}
} catch (Exception $e) {
Mage::getSingleton('checkout/session')->addException($e, $this->__('Can not add item to shopping cart'));
}
}
$cart->save();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}
}