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

标签 php zend-framework zend-framework2

有什么方法可以使正确的 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/

相关文章:

zend-framework - Zend Lucene - 无法搜索数字

PHP fatal error : Class 'Zend\Mvc\Application' not found

zend-framework2 - Zend Framework 2 的多个表

php - cakephp 将数据库字段中的输入数据匹配到文本框

javascript - 如何在 js 中使用输入运行 "str_replace"函数?

php - Laravel 5.1 API 启用 Cors

php - 使用在同一个 ini 文件中定义的 ini 值

php - 如何在 PHP 中执行多个 MySQL 插入

php - 如何最好地选择 PHP 框架 - Laravel、Symfony、Zend 等

php - 在 ZF2 项目中启用 Doctrine 2 缓存