【问题标题】:How to return only JSON from Zend如何从 Zend 只返回 JSON
【发布时间】:2013-01-24 11:59:20
【问题描述】:

我在我的项目中使用 Zend Framework 1.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。还是没有成功。

P.S.:以上大部分方法都来自 Stack Overflow 上提出的问题。

【问题讨论】:

    标签: php json web-services zend-framework rest


    【解决方案1】:

    我喜欢这种方式!

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

    【讨论】:

    • 这个方法我用了一段时间了。我不明白需要所有额外的代码。据我所知,辅助方法会为您处理一切。
    • 这段代码放在哪里?在控制器的动作函数中?
    • @HarisMehmood 您的控制器的操作是放置它的正确位置,因为它是处理请求和准备输出的角色。
    【解决方案2】:

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

    显式禁用布局和视图渲染器:

    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);
    }
    

    【讨论】:

    • 维努的方法更好!
    【解决方案3】:

    您的代码还需要禁用布局,以停止使用标准页面模板包装内容。但更简单的方法是:

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

    JSON 助手会将您的变量编码为 JSON,设置适当的标头并为您禁用布局和视图脚本。

    【讨论】:

      【解决方案4】:

      这要容易得多。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        • 2018-07-23
        • 1970-01-01
        • 2018-12-24
        • 1970-01-01
        • 2012-07-11
        相关资源
        最近更新 更多