Shi*_*ity 3 php zend-framework zend-framework2
有没有办法让正确的JSON输出工作?(在ZF1中替换$ this - > _ heleper-> json-> SendJSON())
public function ajaxSectionAction() {
return new JsonModel(array(
'some_parameter' => 'some value',
'success' => true,
));
}
Run Code Online (Sandbox Code Playgroud)
因为它会引发错误:
> Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException'
> with message 'SmartyModule\View\Renderer\SmartyRenderer::render:
> Unable to render template ...
Run Code Online (Sandbox Code Playgroud)
Moh*_*ibi 10
Rob Allen写了一篇关于它的文章: 从ZF2控制器动作返回JSON
如果要返回JsonModel,则必须将JsonStrategy添加到view_manager:
//module.config.php
return array(
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy',
),
),
)
Run Code Online (Sandbox Code Playgroud)
然后从动作控制器返回一个JsonModel:
public function indexAction()
{
$result = new JsonModel(array(
...
));
return $result;
}
Run Code Online (Sandbox Code Playgroud)
另一种方法,您也可以尝试使用此代码返回每个数据而不进行视图渲染:
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent('some data');
return $response;
Run Code Online (Sandbox Code Playgroud)
您可以尝试$response->setContent(json_encode(array(...)));或:
$jsonModel = new \Zend\View\Model\JsonModel(array(...));
$response->setContent($jsonModel->serialize());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4389 次 |
| 最近记录: |