web*_*com 20 php json zend-framework-mvc zend-framework2
到目前为止,我已经想通了如何返回Zend框架2.首先一个典型的JSON响应,我加入ViewJsonStrategy到strategies了部分view_manager配置.然后,ViewModel我返回一个JsonModel设置了所有变量的实例,而不是从控制器操作返回一个实例.
既然我已经想到了这一点,我需要了解如何渲染视图并在JSON响应中返回它.在ZF1中,我能够使用$this->view->render($scriptName),它将HTML作为字符串返回.在ZF2中,该Zend\View\View::render(...)方法返回void.
那么......我如何渲染HTML视图脚本并在一个请求中以JSON响应返回它?
这就是我现在所拥有的:
if ($this->getRequest()->isXmlHttpRequest()) {
$jsonModel = new JsonModel(...);
/* @todo Render HTML script into `$html` variable, and add to `JsonModel` */
return $jsonModel;
} else {
return new ViewModel(...);
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*Sam 48
好吧,我想我终于明白你在做什么了.我找到了一个符合您标准的解决方案.虽然我确信还有改进的余地,因为有一些讨厌的手工要做......
public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest()) {
return array();
}
$htmlViewPart = new ViewModel();
$htmlViewPart->setTerminal(true)
->setTemplate('module/controller/action')
->setVariables(array(
'key' => 'value'
));
$htmlOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($htmlViewPart);
$jsonModel = new JsonModel();
$jsonModel->setVariables(array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1,2,3,4,5,6)
));
return $jsonModel;
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我创建的templateMap是......令人讨厌的...它很烦人,我相信它可以通过相当多的改进来改进.这是一个有效的解决方案,但不是一个干净的解决方案.也许某种程度上,人们可以从ServiceLocator中获取可能已经实例化的默认PhpRenderer,并使用它的模板和路径映射,然后它应该更干净.
感谢@DrBeza的评论,需要完成的工作可能会减少很多.现在,正如我最初想要的那样,我们将抓取viewrenderer,其中所有模板映射完好无损,并直接渲染ViewModel.唯一重要的因素是您需要指定要呈现的完全限定模板(例如:"$ module/$ controller/$ action")
我希望这会让你开始;)
PS:响应如下:
Object:
html: "<h1>Hello World</h1>"
jsonArray: Array[6]
jsonVar1: "jsonVal2"
Run Code Online (Sandbox Code Playgroud)
您可以使用更简单的方法为JSON响应呈现视图.
public function indexAction() {
$partial = $this->getServiceLocator()->get('viewhelpermanager')->get('partial');
$data = array(
'html' => $partial('MyModule/MyPartView.phtml', array("key" => "value")),
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1, 2, 3, 4, 5, 6));
$isAjax = $this->getRequest()->isXmlHttpRequest());
return isAjax?new JsonModel($data):new ViewModel($data);
}
Run Code Online (Sandbox Code Playgroud)
请注意在使用JsonModel类之前,您需要在模块的module.config.php文件中配置View Manager .
'view_manager' => array(
.................
'strategies' => array(
'ViewJsonStrategy',
),
.................
),
Run Code Online (Sandbox Code Playgroud)
这对我有用,希望对你有所帮助.
| 归档时间: |
|
| 查看次数: |
27995 次 |
| 最近记录: |