我正在尝试实现以下内容:
简单的 Controller 和 Action 。操作应根据请求返回 2 种类型的响应:
HTML in case of ordinary request (text\html),
JSON in case of ajax request (application\json)
我已经通过 Controller 插件设法做到了这一点,但这需要编写
return $this->myCallBackFunction($data)
在每个 Action 中。如果我不想对整个 Controller 执行此操作怎么办?试图弄清楚如何通过事件监听器实现它,但未能成功。
任何提示或某些文章的链接将不胜感激!
最佳答案
ZF2 具有 acceptable view model selector专门用于此目的的 Controller 插件。它将根据您通过查看客户端发送的 Accepts header 定义的映射来选择合适的 ViewModel。
对于您的示例,您首先需要通过将 JSON View 策略添加到您的 View 管理器配置(通常在 module.config.php
中)来启用它:
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy'
)
),
(很可能你已经在那里有一个 view_manager 键,在这种情况下,将“策略”部分添加到你当前的配置中。)
然后在您的 Controller 中调用 Controller 插件,使用您的映射作为参数:
class IndexController extends AbstractActionController
{
protected $acceptMapping = array(
'Zend\View\Model\ViewModel' => array(
'text/html'
),
'Zend\View\Model\JsonModel' => array(
'application/json'
)
);
public function indexAction()
{
$viewModel = $this->acceptableViewModelSelector($this->acceptMapping);
return $viewModel;
}
}
这将为标准请求返回一个普通的 ViewModel,并为接受 JSON 响应(即 AJAX 请求)的请求返回一个 JsonModel。
您分配给 JsonModel 的任何变量都将显示在 JSON 输出中。
关于json - ZF2 查看策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18534327/