ZF2: return JSON for Ajax call only

I am trying to learn ZF2. I have a page that uses Ajax to get some data. The ZF2 function should return a JSON string.

<?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; } } 

But I keep getting this fatal error:

 ( ! ) 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 

I searched for this error and the best way to make ajax calls in ZF2, however the results for ZF1 or ZF2 beta versions continue to appear and do not work. Thanks for any advice you can give.

+4
source share
2 answers

Hmm, this error pretty much implies that it is trying to access the default rendering strategy, which is rather strange ... Have you added JsonStrategy to your view_manager?

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

In addition, it is recommended that you set the correct accept header inside of you ajax calls only to accept the application/json content type. It should work with this set. Out of curiosity, however, are there modules/__NAMESPACE__/view/__namespace__/documents/get-tree-data.phtml ?

+16
source

Try something like this ...

 $response = $this->getResponse(); $response->setStatusCode(200); $jsonArray = {.....} $response->setBody($jsonArray); return $response; 

And be sure to add ViewJsonStrategy to your module configuration.

0
source

Source: https://habr.com/ru/post/1436497/


All Articles