how to set a custom view in zend-framework2

怎甘沉沦 提交于 2019-12-11 14:54:58

问题


I am trying to return a custom view using ajax in zend framework2. This view may be changed dynamically according to the condition in ajax call.. So how i can return a full view through ajax in zf2 ?


回答1:


You can return a full view through ajax in the same way as you would return a full view through your browsers location bar. If you just want to return html, then simply return a view model in the same way you usually would. You may want to disable the layout, this can be done with:

$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;

Alternatively, if you want to return JSON, you can use the json view strategy, it needs to be enabled in your module.config.php:

'strategies' => array(
    'ViewJsonStrategy',
), 

then, in your action, return a new JsonModel instead of a ViewModel.




回答2:


Attaching the ViewJsonStrategy will make this event listener run with each request checking for the JsonModel in the action output.

It can be quicker and more efficient to simply return the json content directly:

return $this->getResponse()->setContent(json_encode($your_data));

If required you can also add the header line the Content-type: application/json line.



来源:https://stackoverflow.com/questions/17804851/how-to-set-a-custom-view-in-zend-framework2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!