php 如何从 CakePHP 2.2 控制器返回 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12962870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return JSON from a CakePHP 2.2 controller?
提问by sergserg
I'm invoking a controller function:
我正在调用一个控制器函数:
$.get("http://localhost/universityapp/courses/listnames", function(data){
alert("Data Loaded: " + data);
});
And in my Controller:
在我的控制器中:
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
}
And in that View:
在该视图中:
<?php echo json_encode($asdf); ?>
However, the Action is returning the entire page including the Layout content (header, footer, navigation).
但是,Action 将返回整个页面,包括布局内容(页眉、页脚、导航)。
What am I missing here? How can I return just the JSON data without the Layout content?
我在这里缺少什么?如何仅返回 JSON 数据而没有 Layout 内容?
回答by Guilherme Ferreira
Set autoRender=falseand return json_encode($code):-
设置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)
)));
}
回答by Moyed Ansari
You need to disable layout like this
您需要像这样禁用布局
$this->layout = null ;
Now your action will become
现在你的行动将变成
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
}
回答by Anil kumar
You can try any of the following to return json response (I've taken failure case here to return json response) :
您可以尝试以下任何一种方法来返回 json 响应(我在这里采用了失败案例来返回 json 响应):
public function action() {
$this->response->body(json_encode(array(
'success' => 0,
'message' => 'Invalid request.'
)));
$this->response->send();
$this->_stop();
}
OR
或者
public function action() {
$this->layout = false;
$this->autoRender = false;
return json_encode(array(
'success' => 0,
'message' => 'Invalid request.'
));
}

