Proper JSON output in ZF2 without template rendering
php, zend-framework, zend-framework2
Solution
Rob Allen has written an article about it: Returning JSON from a ZF2 controller action
If you want to return a JsonModel, You have to add JsonStrategy to your view_manager:
//module.config.php
return array(
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy',
),
),
)
Then return a JsonModel from action controller:
public function indexAction()
{
$result = new JsonModel(array(
...
));
return $result;
}
Another way, Also you can try this code to return every data without view rendering:
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent('some data');
return $response;
You can try `$response->setContent(json_encode(array(...)));` or :
$jsonModel = new \Zend\View\Model\JsonModel(array(...));
$response->setContent($jsonModel->serialize());
Problem
Is there any way to make proper JSON output work? (alternative to $this->_heleper->json->SendJSON() in ZF1) ``` public function ajaxSectionAction() { return new JsonModel(array( 'some_parameter' => 'some value', 'success' => true, )); } ``` Bacause it throws an error: ``` > Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' > with message 'SmartyModule\View\Renderer\SmartyRenderer::render: > Unable to render template ... ```