有什么方法可以使正确的 JSON 输出工作吗? (替代 ZF1 中的 $this->_heleper->json->SendJSON())
public function ajaxSectionAction() {
return new JsonModel(array(
'some_parameter' => 'some value',
'success' => true,
));
}
因为它抛出一个错误:
> Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException'
> with message 'SmartyModule\View\Renderer\SmartyRenderer::render:
> Unable to render template ...
最佳答案
Rob Allen 写了一篇关于它的文章: Returning JSON from a ZF2 controller action
如果你想返回一个 JsonModel,你必须将 JsonStrategy 添加到你的 view_manager:
//module.config.php
return array(
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy',
),
),
)
然后从 Action Controller 返回一个 JsonModel:
public function indexAction()
{
$result = new JsonModel(array(
...
));
return $result;
}
另一种方法,您也可以尝试使用此代码返回所有数据而无需 View 渲染:
$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());
关于php - ZF2 中正确的 JSON 输出,无需模板渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452549/