2013-12-08 43 views
3

有什麼方法可以使正確的JSON輸出工作嗎? (替代$此 - > _ heleper-> json-> SendJSON()在ZF1在沒有模板渲染的情況下在ZF2中正確輸出JSON

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

Bacause它拋出一個錯誤:

> Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' 

> with message 'SmartyModule\View\Renderer\SmartyRenderer::render: 

> Unable to render template ... 

回答

6

羅布·艾倫寫了一個關於它的文章: Returning JSON from a ZF2 controller action

如果你想返回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()); 
+0

這是混亂的方式,我看不出這和Zend_Json :: encode()之間的優點 – ShiftedReality

+0

我更新了答案。最好的方法是JsonModel並查看策略。但是你可以使用Response來返回每個數據,比如json。 –

相關問題