how to set a custom view in zend-framework2

2019-08-28 17:04发布

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 ?

2条回答
Luminary・发光体
2楼-- · 2019-08-28 17:20

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.

查看更多
疯言疯语
3楼-- · 2019-08-28 17:33

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.

查看更多
登录 后发表回答