0

I'm developing a Magento extension and having trouble trying to get it to run javascript when an item is added to cart.

In config.xml I have an observer

<checkout_cart_product_add_after>

In Observer.php

public function itemAddedToCart(Varien_Event_Observer $observer){}

This is firing (I can test by echo-ing). But how do I get it to inject a block of javascript (preferably into the footer)?

Thanks in advance.

UPDATE: Used Chris' solution, but instead of registry I used the session to avoid potential multi-user issues:

In Observer.php

public function itemAddedToCart(Varien_Event_Observer $observer){}
    $itemAddedToCart = 'true';
    Mage::getSingleton('core/session')->setItemAddedToCart($itemAddedToCart);

In my custom block (script.phtml):

<?php if($itemAddedToCart) : ?>
    <script type="text/javascript">
        alert(<?php echo '"' . $this->__($itemAddedToCart) . '"' ?>);
    </script>
    <?php 
        // Clear itemAddedToCart session variable:
        Mage::getSingleton('core/session')->unsItemAddedToCart(); 
    ?>
<?php endif; ?>

Hope this helps others.

4

1 回答 1

2

您应该能够通过扩展的布局 XML 文件中的 XML 来完成此操作。

<catalog_product_view>
    <reference name="footer">
        <block type="core/template" name="INSERT_CUSTOM_NAME_HERE" template="path/to/your/phtml/file.phtml" />
    </reference>
</catalog_product_view>

确保删除缓存,因为 XML 更新仅在刷新缓存后应用。

如果您使用默认的 Magento 主题,则无需调用此模板,因为它会自动调用所有 children $this->getChildHtml('');。但是,如果您使用的是自定义主题,您应该将其添加到您的 footer.phtml:$this->getChildHtml('INSERT_CUSTOM_NAME_HERE');中。

或者,如果您想在购物车页面上使用 javascript,您应该替换<catalog_product_view><checkout_cart_index>.

于 2013-05-09T21:13:09.373 回答