Returning JSON from a ZF2 controller action

http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/

The new view layer in Zend Framework 2 can be set up to return JSON rather than rendered HTML relatively easily. There are two steps to this:

Set up the JsonStrategy

Firstly we need to set up the view's JsonStrategy to check to a situation when returning JSON is required and then to render out JSON for us. The JsonStrategy will cause theJsonRenderer to be run in two situations:

  1. The view model returned by the controller action is a JsonModel
  2. The HTTP Accept header sent in the Request include "application/json"

To enable the JsonStrategy, we simply configure it in the module's config.php file:

module/Application/config/module.config.php:

    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
            'index/index'   => __DIR__ . '/../view/index/index.phtml',
            'error/404'     => __DIR__ . '/../view/error/404.phtml',
            'error/index'   => __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            'application' => __DIR__ . '/../view',
        ),
        'strategies' => array(
            'ViewJsonStrategy',
        ),
    ),

As you can see, in the view_manager() add ViewJsonStrategy to the strategies array.

Return a JsonModel from the controller action

To send JSON to the client when the Accept header isn't application/json, we use aJsonModel in a controller action like this:

module/Application/src/Application/Controller/IndexController.php:

namespace Application\Controller;

use Zend\Mvc\Controller\ActionController;
use Zend\ViewModel\ViewModel;
use Zend\ViewModel\JsonModel;

class IndexController extends ActionController
{
    public function indexAction()
    {
        $result = new JsonModel(array(
	    'some_parameter' => 'some value',
            'success'=>true,
        ));

        return $result;
    }
}

The output will now be JSON. Obviously, if you're sending JSON back based on the Accept header, then you can return a normal ViewModel.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值