2012-09-27 53 views
4

我努力學習ZF2。我有一個使用Ajax獲取一些數據的頁面。 ZF2函數應該返回一個JSON字符串。ZF2:返回JSON只針對AJAX調用

<?php 
namespace Application\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel; 
use Zend\View\Model\JsonModel; 

class DocumentsController extends AbstractActionController { 

    public function indexAction() { 

    } 

    public function getTreeDataAction() { 
     $json = new JsonModel(array(
        'title' => 'Some Title' 
       )); 
     return $json; 
    } 

} 

但我不斷收到這種致命的錯誤:

(!) Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template "application/documents/get-tree-data"; resolver could not resolve to a file' in ../vendor/ZF2/library/Zend/View/Renderer/PhpRenderer.php on line 451 

我一直在尋找周圍的這個錯誤,並作出ZF2 Ajax調用的最佳方式,但結果ZF1或ZF2貝塔滾滾而來不起作用。感謝您提供任何建議。

回答

15

嗯,這個錯誤幾乎意味着它試圖訪問默認渲染策略,這是相當奇怪的......你已經添加了JsonStrategy你view_manager?

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

而且它的設置正確接受標頭在你的Ajax調用只接受application/json內容類型是個好主意。有了這套,它應該實際上工作。出於好奇,modules/__NAMESPACE__/view/__namespace__/documents/get-tree-data.phtml是否存在?

+0

感謝我無法相信我錯過了羅布·艾倫的DevNotes的一部分。是的,我有get-tree-data.phtml,但使用JsonModel它沒有找到它。 –

+0

冒先風險,我有一些代碼來幫助與zf2的AJAX請求:http://github.com/superdweebie/jsonController。它有三個新的抽象控制器來處理jsonRest,jsonRPC和jsonp請求。 – superdweebie

0

嘗試這樣的事情......

$response = $this->getResponse(); 
$response->setStatusCode(200); 

$jsonArray = {.....} 
$response->setBody($jsonArray); 

return $response; 

並確保您添加ViewJsonStrategy到您的模塊配置爲好。