【发布时间】:2012-09-08 02:21:27
【问题描述】:
我正在尝试使用观察者来修改添加到购物车控制器操作的响应,但仅限于 AJAX 请求的上下文中。
我的观察者 被 调用并且我的 JS 检索数据正常,我已经通过在我的观察者函数 cartAdd() 中放置一个 die() 并验证我正在使用的响应开发者控制台来验证这一点查看我的 Magento 回复的结果。所以 JS 不是这里的问题。
我的主要问题是我似乎无法通过正常功能修改响应。我通过使用$observer->getEvent()->getControllerAction()->getResponse() 获取请求,然后通过setHeader() 或setBody() 或任何其他修改响应的函数对其进行更改,但对响应绝对没有影响!
有人知道为什么我无法修改观察者的响应吗?
在/app/code/local/mynamespace/mymodule/etc/config.xml:
<frontend>
....
<events>
<controller_action_predispatch_checkout_cart_add>
<observers>
<mymodule_cart_add>
<type>singleton</type>
<class>mymodule/observer</class>
<method>cartAdd</method>
</mymodule_cart_add>
</observers>
</controller_action_predispatch_checkout_cart_add>
</events>
</frontend>
在/app/code/local/mynamespace/mymodule/Model/Observer.php:
public function cartAdd(Varien_Event_Observer $observer)
{
$controllerAction = $observer->getEvent()->getControllerAction();
if($controllerAction->getRequest()->isAjax()) {
$response = $controllerAction->getResponse();
// I've even tried using:
// $response = Mage::app()->getResponse();
$response->setHeader('HTTP/1.1','403 Forbidden'); //using this because i will need it in my final code and it will make it immediatly obvious the response has been changed
$response->setHeader('Content-type', 'application/json');
$response->setBody('hello world!!!!');
// this is to stop the product from being added to the cart
$controllerAction->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);
}
}
请注意:我知道这段代码根本不会 AJAXify 添加到购物车(这是我的最终目标)。目前我只是想解决这个问题
我最终只是获得了您在运行添加到购物车操作后最终会访问的页面内容:
【问题讨论】:
-
99% 确定在触发动态预调度事件后,请求上设置了不同的重定向。现在确认,将回答。
标签: magento magento-1.7