我需要將ajax請求轉發給當前控制器的其他Action方法。我使用Forward插件,但它不起作用。還有就是手冊中有關如何使用轉發插件的例子:ZF2:控制器的Forward插件不起作用。如何使它工作?
$foo = $this->forward()->dispatch('foo', array('action' => 'process'));
return array(
'somekey' => $somevalue,
'foo' => $foo,
);
我的代碼:
// From Ajax on the page. I apply to the indexAction of FooController,
// I use RegEx route
xhr.open('get', '/fooindex', true);
// My Controller
namespace Foo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
// I extend the AbstractActionController, the manual says it's important for the Forward Plugin to work
class FooController extends AbstractActionController {
// This is the action I send my request from Ajax
public function indexAction() {
// if the request if Ajax request I forward the run to the nextAction method
if ($this->getRequest()->isXmlHttpRequest()) {
// I do as manual says
$rs = $this->forward()->dispatch('FooController', array('action' => 'next'));
}
}
public function nextAction() {
// And I just want to stop here to see that the Forward Plugin works
// But control doesn't reach here
exit('nextAction');
}
}
我在控制檯得到的錯誤是:
GET http://test.localhost/fooindex 500 (Internal Server Error)
如果我不要使用轉發一切正常,請求indexAction
就好了。只有向前引發錯誤。
From the manual, about The Forward Plugin:
對於正向插件工作時,控制器調用它必須是 ServiceLocatorAware;否則,該插件將無法檢索到所請求的控制器的配置和注入實例 。
From the manual, about Available Controllers:
實施上述各接口中的是在冗餘的教訓; 你不會經常想要這樣做。因此,我們開發了兩個抽象的基礎控制器,您可以擴展以開始使用。
AbstractActionController實現以下每個接口:
的Zend \ STDLIB \ DispatchableInterface 的Zend \的mvc \ InjectApplicationEventInterface 的Zend \的ServiceManager \ ServiceLocatorAwareInterface 的Zend \ eventmanager進行\ EventManagerAwareInterface
所以我FooController
延伸AbstractActionController
,它實現了ServiceLocatorAwareInterface
,所以Forward必須工作,但它不會。我錯過了什麼?如何使它工作?