【问题标题】:How to return JSON from a CakePHP 2.2 controller?如何从 CakePHP 2.2 控制器返回 JSON?
【发布时间】:2012-10-18 20:07:17
【问题描述】:

我正在调用一个控制器函数:

$.get("http://localhost/universityapp/courses/listnames", function(data){
    alert("Data Loaded: " + data);
});

在我的控制器中:

public function listnames() {
    $data = Array(
        "name" => "Sergio",
        "age" => 23
    );
    $this->set('test', $data);
    $this->render('/Elements/ajaxreturn'); // This View is declared at /Elements/ajaxreturn.ctp
}

在那个视图中:

<?php echo json_encode($asdf); ?>

但是,Action 会返回整个页面,包括布局内容(页眉、页脚、导航)。

我在这里缺少什么?如何只返回没有布局内容的 JSON 数据?

【问题讨论】:

  • 设置 $this->layout = null ;在列表名称中
  • @MoyedAnsari:如果你把它写成你的答案,我会接受它作为解决方案。
  • 已发布答案希望这对你有用
  • 一定要$this-&gt;response-&gt;type('json'); ????

标签: php json cakephp controller cakephp-2.2


【解决方案1】:

设置autoRender=false并返回json_encode($code):-

public function returningJsonData($estado_id){
    $this->autoRender = false;

    return json_encode($this->ModelBla->find('first',array(
        'conditions'=>array('Bla.bla_child_id'=>$estado_id)
    )));
}

【讨论】:

  • +1 这种简单情况的最简单解决方案。
【解决方案2】:

你需要像这样禁用布局

$this->layout = null ;

现在你的动作会变成

public function listnames() {
    $this->layout = null ;
    $data = Array(
        "name" => "Sergio",
        "age" => 23
    );
    $this->set('test', $data);
    $this->render('/Elements/ajaxreturn'); // This View is declared at /Elements/ajaxreturn.ctp
}

【讨论】:

    【解决方案3】:

    阅读手册中的JsonView

    【讨论】:

      【解决方案4】:

      您可以尝试以下任何一种方法来返回 json 响应(我在这里采用了失败案例来返回 json 响应):

      public function action() {
          $this->response->body(json_encode(array(
              'success' => 0,
              'message' => 'Invalid request.'
          )));
      
          $this->response->send();
          $this->_stop();
      }
      

      public function action() {
          $this->layout = false;
          $this->autoRender = false;
          return json_encode(array(
              'success' => 0,
              'message' => 'Invalid request.'
          ));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多