我在我的项目中使用Zend Framework1.x。我想为调用者函数创建一个只返回JSON字符串的Web服务。我尝试使用Zend_Controller_Action
,并应用了这些方法:
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);
7.
$this->view->_response = $arrResult;
但是当我使用cURL获取结果时,它返回的是由一些HTML标记包围的JSON字符串。然后,我尝试使用上面的选项来使用Zend_Rest_Controller
。它仍然没有成功。
附言:上面的大多数方法都来自于在Stack Overflow上被问到的问题。
发布于 2013-02-09 00:58:51
我喜欢这样!
//encode your data into JSON and send the response
$this->_helper->json($myArrayofData);
//nothing else will get executed after the line above
发布于 2013-02-09 05:42:43
您需要禁用布局和视图渲染。
显式禁用布局和视图渲染器:
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 helper将为您禁用布局和视图渲染器。
public function init()
{
$this->_helper->contextSwitch()
->addActionContext('getJsonResponse', array('json'))
->initContext();
}
public function getJsonResponseAction()
{
$jsonData = ''; // your json response
return $this->_helper->json->sendJson($jsonData);
}
发布于 2013-02-09 00:53:31
您的代码还需要禁用布局,以便停止使用标准页面模板包装内容。但一种更简单的方法是:
$this->getHelper('json')->sendJson($arrResult);
JSON helper会将您的变量编码为JSON,设置适当的头文件,并为您禁用布局和视图脚本。
https://stackoverflow.com/questions/14777324
复制相似问题