how to set a custom view in zend-framework2

2019-08-28 16:48发布

问题:

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.