2013-07-31 50 views
1

我正在编写REST API,并希望以JSON格式返回响应。所以,我读了关于'ContextSwitch'的内容。但我不能让它改变头到'application/json'并将数据转换成json。Zend Framework 1.12和'ContextSwitch'帮手

这里是我的控制器代码:

public function preDispatch() 
{ 

    $this->getRequest()->setParam('format', 'json'); 
    $this->_helper->layout()->disableLayout(); 
    $this->_helper->viewRenderer->setNoRender(true); 
} 


public function _init() 
{ 

    $contextSwitch = $this->_helper->getHelper('contextSwitch'); 
    $contextSwitch ->addActionContext('post', 'json') 
        ->initContext('json'); 
} 

public function postAction() 
{ 
    echo 'test'; 

} 

当我检查响应与curl命令行工具,我收到:

< Content-Length: 4 
< Content-Type: text/html 
< 
* Connection #0 to host localhost left intact 
test* Closing connection #0 

为什么头和数据没有改变?我该如何解决它?

回答

1

看起来像_init()方法根本没有执行。尝试将其重命名为init()

+0

谢谢,问题是在下划线。 – Tamara

0

,因为我觉得你的代码已经丢失了一些步骤调用上下文切换帮手

这里工作示例我使用的上下文切换的REST API

只是去扔this API example,使你的脚本工作

希望这会帮助你。