How to render ZF2 view within JSON response?

旧时模样 提交于 2019-11-27 03:28:20
Sam

OK, i think i finally understood what you're doing. I've found a solution that i think matches your criteria. Though i am sure that there is room for improvement, as there's some nasty handwork to be done...

public function indexAction()
{
  if (!$this->getRequest()->isXmlHttpRequest()) {
    return array();
  }

  $htmlViewPart = new ViewModel();
  $htmlViewPart->setTerminal(true)
               ->setTemplate('module/controller/action')
               ->setVariables(array(
                  'key' => 'value'
               ));

  $htmlOutput = $this->getServiceLocator()
                     ->get('viewrenderer')
                     ->render($htmlViewPart);

  $jsonModel = new JsonModel();
  $jsonModel->setVariables(array(
    'html' => $htmlOutput,
    'jsonVar1' => 'jsonVal2',
    'jsonArray' => array(1,2,3,4,5,6)
  ));

  return $jsonModel;
}

As you can see, the templateMap i create is ... nasty ... it's annoying and i'm sure it can be improved by quite a bit. It's a working solution but just not a clean one. Maybe somehow one would be able to grab the, probably already instantiated, default PhpRenderer from the ServiceLocator with it's template- and path-mapping and then it should be cleaner.

Thanks to the comment ot @DrBeza the work needed to be done could be reduced by a fair amount. Now, as I'd initially wanted, we will grab the viewrenderer with all the template mapping intact and simply render the ViewModel directly. The only important factor is that you need to specify the fully qualified template to render (e.g.: "$module/$controller/$action")

I hope this will get you started though ;)

PS: Response looks like this:

Object:
    html: "<h1>Hello World</h1>"
    jsonArray: Array[6]
    jsonVar1: "jsonVal2"

You can use more easy way to render view for your JSON response.

public function indexAction() {
    $partial = $this->getServiceLocator()->get('viewhelpermanager')->get('partial');
    $data = array(
            'html' => $partial('MyModule/MyPartView.phtml', array("key" => "value")),
            'jsonVar1' => 'jsonVal2',
            'jsonArray' => array(1, 2, 3, 4, 5, 6));
    $isAjax = $this->getRequest()->isXmlHttpRequest());
    return isAjax?new JsonModel($data):new ViewModel($data);
}

Please note before use JsonModel class you need to config View Manager in module.config.php file of your module.

'view_manager' => array(
        .................
        'strategies' => array(
            'ViewJsonStrategy',
        ),
        .................
    ),

it is work for me and hope it help you.

In ZF 3 you can achieve the same result with this code

MyControllerFactory.php

public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
    $renderer = $container->get('ViewRenderer');

    return new MyController(
        $renderer
    );
}

MyController.php

private $renderer;

public function __construct($renderer) {
    $this->renderer = $renderer;
}

public function indexAction() {

    $htmlViewPart = new ViewModel();
    $htmlViewPart
            ->setTerminal(true)
            ->setTemplate('module/controller/action')
            ->setVariables(array('key' => 'value'));

    $htmlOutput = $this->renderer->render($htmlViewPart);

    $json = \Zend\Json\Json::encode(
        array(
            'html' => $htmlOutput,
            'jsonVar1' => 'jsonVal2',
            'jsonArray' => array(1, 2, 3, 4, 5, 6)
        )
    );

    $response = $this->getResponse();
    $response->setContent($json);

    $response->getHeaders()->addHeaders(array(
        'Content-Type' => 'application/json',
    ));
    return $this->response;
}

As usual framework developer mess thing about AJAX following the rule why simple if might be complex Here is simple solution in controller script

public function checkloginAction()
{
   // some hosts need to this some not 
   //header ("Content-type: application/json");  // this work
   // prepare json aray ....
   $arr = $array("some" => .....);
   echo json_encode($arr); // this works
   exit;
}

This works in ZF1 and ZF2 as well No need of view scrpt at all

If you use advise of ZF2 creator

use Zend\View\Model\JsonModel;
....


 $result = new JsonModel($arr);
 return $result;

AJAX got null as response at least in zf 2.0.0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!