Gia*_*inh 23 php rest json web-services zend-framework
我正在为我的项目使用Zend Framework 1.x. 我想创建一个Web服务只返回调用函数的JSON字符串.我尝试使用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使用上面的选项.它仍然没有成功.
PS:上面的大多数方法来自Stack Overflow上提出的问题.
Ven*_*enu 45
我喜欢这样!
//encode your data into JSON and send the response
$this->_helper->json($myArrayofData);
//nothing else will get executed after the line above
Ger*_*che 12
您需要禁用布局和视图渲染.
显式禁用布局和视图渲染器:
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);
}
您的代码也需要禁用布局,以便停止使用标准页面模板包装的内容.但更简单的方法就是:
$this->getHelper('json')->sendJson($arrResult);
JSON帮助程序将您的变量编码为JSON,设置适当的标头并为您禁用布局和查看脚本.
| 归档时间: | 
 | 
| 查看次数: | 26643 次 | 
| 最近记录: |