Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper JSON output in ZF2 without template rendering

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 ...
like image 233
ShiftedReality Avatar asked Feb 02 '26 07:02

ShiftedReality


1 Answers

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());
like image 135
Mohammad Mehdi Habibi Avatar answered Feb 05 '26 09:02

Mohammad Mehdi Habibi