2013-02-08 83 views
18

我对我的项目使用了Zend Framework 1.x。我想为调用者函数创建一个只返回JSON字符串的Web服务。我试图使用Zend_Controller_Action和施加那些方法:如何仅从Zend返回JSON

1.

$this->getResponse() 
    ->setHeader('Content-type', 'text/plain') 
    ->setBody(json_encode($arrResult)); 

2.

$this->_helper->getHelper('contextSwitch') 
       ->addActionContext('nctpaymenthandler', 'json') 
       ->initContext(); 

3.

header('Content-type: application/json'); 

4.

$this->_response->setHeader('Content-type', 'application/json'); 

5.

echo Zend_Json::encode($arrResult); 
exit; 

6.

return json_encode($arrResult); 
$this->view->_response = $arrResult; 

但是,当我用卷曲得到的结果,它返回用JSON字符串一些HTML标签包围。然后我尝试使用上面的选项Zend_Rest_Controller。它仍然没有成功。

P.S .:上面的大多数方法都来自Stack Overflow上提出的问题。

回答

32

我喜欢这种方式!

//encode your data into JSON and send the response 
$this->_helper->json($myArrayofData); 
//nothing else will get executed after the line above 
+3

我已经使用了这种方法一段时间了。我不明白需要所有额外的代码。据我所知,辅助方法可以处理所有的事情。 – David 2013-10-01 19:09:23

+0

在哪里放这个代码?在控制器的动作功能? – 2016-03-15 13:55:40

+0

@HarisMehmood你的控制者的行为是正确的地方,因为它是处理请求和准备输出的角色。 – Tim 2016-04-18 11:54:37

7

您的代码需要禁用布局,以便停止使用标准页面模板包装的内容。但一个更容易的办法也只是:

$this->getHelper('json')->sendJson($arrResult); 

JSON助手将您的变量编码为JSON,设置相应的头文件和禁用布局和脚本为您服务。

9

您需要禁用布局和视图渲染。

明确禁止的布局和视图渲染:

public function getJsonResponseAction() 
{ 
    $this->getHelper('Layout') 
     ->disableLayout(); 

    $this->getHelper('ViewRenderer') 
     ->setNoRender(); 

    $this->getResponse() 
     ->setHeader('Content-Type', 'application/json'); 

    // should the content type should be UTF-8? 
    // $this->getResponse() 
    //  ->setHeader('Content-Type', 'application/json; charset=UTF-8'); 

    // ECHO JSON HERE 

    return; 
} 

如果你使用你需要一个JSON上下文到行动的JSON控制器动作助手。在这种情况下,json助手将禁用布局并查看渲染器。

public function init() 
{ 
    $this->_helper->contextSwitch() 
     ->addActionContext('getJsonResponse', array('json')) 
     ->initContext(); 
} 

public function getJsonResponseAction() 
{ 
    $jsonData = ''; // your json response 

    return $this->_helper->json->sendJson($jsonData); 
} 
+0

Venu的方法更好! – Naelyth 2014-03-19 14:59:47

0

这很容易。

public function init() 
{ 
    parent::init(); 
    $this->_helper->contextSwitch() 
     ->addActionContext('foo', 'json') 
     ->initContext('json'); 
} 

public function fooAction() 
{ 
    $this->view->foo = 'bar'; 
}