ZF2中正确的JSON输出,无需模板渲染


Proper JSON output in ZF2 without template rendering

有什么方法可以使JSON输出正常工作吗?(ZF1中$this->_heleper->json->SendJSON()的替代方案)

    public function ajaxSectionAction() {
return new JsonModel(array(
    'some_parameter' => 'some value',
    'success' => true,
));
}

B因为它抛出了一个错误:

> Fatal error: Uncaught exception 'Zend'View'Exception'RuntimeException'
> with message 'SmartyModule'View'Renderer'SmartyRenderer::render:
> Unable to render template ...

Rob Allen写了一篇关于它的文章:从ZF2控制器操作返回JSON

如果你想返回JsonModel,你必须将JsonStrategy添加到你的view_manager:

//module.config.php
return array(
    'view_manager' => array(
        'strategies' => array(
           'ViewJsonStrategy',
        ),
    ),
)

然后从动作控制器返回JsonModel:

public function indexAction()
{
    $result = new JsonModel(array(
        ...
    ));
    return $result;
}

另一种方法,你也可以尝试这个代码来返回每个数据,而不需要视图渲染:

$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent('some data');
return $response;

您可以尝试$response->setContent(json_encode(array(...)));或:

$jsonModel = new 'Zend'View'Model'JsonModel(array(...));
$response->setContent($jsonModel->serialize());