如何让zend(1.12)控制器中的每个动作都返回JSON?

时间:2015-06-23 13:11:54

标签: json zend-framework

我有一个纯粹用于API的控制器(没有视图或布局)。

我希望每个操作都返回JSON格式,并且响应中的Content-Type为application/json

我可以通过使用控制器postDispatch()来实现标题部分,但是找不到从单个位置执行json_encode()的方法(我知道我可以从每个操作中执行它但是我希望它集中)。

我甚至试图使用插件来操纵请求体,但由于某些原因我不清楚它总是空的。

目前我的解决方案如下:

public function init()
{
    // no Layout
    $this->_helper->layout()->disableLayout();
    // no views
    $this->_helper->viewRenderer->setNoRender(true);
}

public function indexAction()
{
    $data = array("likes","to","sleep");
    echo Zend_Json::encode($data);
}

public function postDispatch()
{
    $this->getResponse()->setHeader('Content-Type', 'application/json');
}

现在,如果我只设法在一个地方做echo Zend_Json::encode ......

2 个答案:

答案 0 :(得分:1)

您可以使用ContextSwitch action helper

  

JSON上下文将“Content-Type”响应头设置为“application / json”,将视图脚本后缀设置为“json.phtml”。但是,默认情况下,不需要查看脚本。它将简单地序列化所有视图变量,并立即发出JSON响应。

您需要在控制器中注册它。

class FooController extends \Zend_Controller_Action
{
    public function init()
    {
        $contextSwitch = $this->_helper->getHelper('contextSwitch');
        $contextSwitch->addActionContext('list', 'json')
                      ->addActionContext('bar', 'json')
                      ->initContext('json'); // json arg here means that we only allow json
    }
}

然后,您需要传递网址format中的/module/foo/bar/format/json参数或查询参数?format=json

答案 1 :(得分:0)

您可以创建自己的controller plugin

>>> import copy >>> list1 = [1,2,3,4,5] >>> list2 = copy.copy(list1) >>> for i in range(len(list2)): ... list2[i] += 1 ... >>> list1 [1, 2, 3, 4, 5] 中关闭布局和视图渲染器,并在preDispatch设置内容类型标题作为响应。

下一个选项是确定要查看的数据。

postDispatch

并在视图脚本中调用json view helper public function indexAction() { $data = array("likes","to","sleep"); $this->view->assign('data', $data); } 并且不使用布局。