CakePHP 2.x 未生成 json 响应
CakePHP 2.x not producing json response
我有一个 Cake 2.x 应用程序。我需要从 PHP 数组提供 JSON 编码的响应,但它没有按预期工作。
在 app/Config/routes.php
我有 Router::parseExtensions('json');
在我的控制器中我有这个代码:
public function ajaxTags()
{
$this->loadModel('Tag');
$tags = $this->Tag->find('list');
var_dump($tags);
die;
}
这会产生我所期望的结果 - 我的 'tags'
数据库 table 中的一个 PHP 数据数组,例如
array(4) {
[1]=> string(14) "United Kingdom"
[2]=> string(6) "France"
[3]=> string(7) ...
}
所以我想做的就是将其作为 JSON 编码数据获取。我已按照 https://book.cakephp.org/2.0/en/views/json-and-xml-views.html
中的说明进行操作
所以在我的 TagsController.php
顶部,我有:
public $components = array('RequestHandler');
然后我尝试按照文档中的说明使用 _serialize
输出它。我不需要 "view" 因为我不想做任何额外的格式化:
public function ajaxTags()
{
$this->loadModel('Tag');
$tags = $this->Tag->find('list');
$this->set('_serialize', array($tags));
}
这给出了以下响应:
null
响应数据被编码为 Content-Type:application/json; charset=UTF-8
(我可以在我的浏览器网络选项卡中看到它)。
我哪里错了?我知道 $tags
里面有数据,因为我之前已经 var_dump
了。为什么它现在给出空输出?
基于documentation,你的操作应该是这样的:
public function ajaxTags()
{
$this->loadModel('Tag');
$tags = $this->Tag->find('list');
$this->set('tags', $tags);
$this->set('_serialize', array('tags'));
}
The _serialize key is a special view variable that indicates which
other view variable(s) should be serialized when using a data view.
您需要将变量 $tags
发送到视图,以便 _serialize
键能够识别并呈现它。
我有一个 Cake 2.x 应用程序。我需要从 PHP 数组提供 JSON 编码的响应,但它没有按预期工作。
在 app/Config/routes.php
我有 Router::parseExtensions('json');
在我的控制器中我有这个代码:
public function ajaxTags()
{
$this->loadModel('Tag');
$tags = $this->Tag->find('list');
var_dump($tags);
die;
}
这会产生我所期望的结果 - 我的 'tags'
数据库 table 中的一个 PHP 数据数组,例如
array(4) {
[1]=> string(14) "United Kingdom"
[2]=> string(6) "France"
[3]=> string(7) ...
}
所以我想做的就是将其作为 JSON 编码数据获取。我已按照 https://book.cakephp.org/2.0/en/views/json-and-xml-views.html
中的说明进行操作所以在我的 TagsController.php
顶部,我有:
public $components = array('RequestHandler');
然后我尝试按照文档中的说明使用 _serialize
输出它。我不需要 "view" 因为我不想做任何额外的格式化:
public function ajaxTags()
{
$this->loadModel('Tag');
$tags = $this->Tag->find('list');
$this->set('_serialize', array($tags));
}
这给出了以下响应:
null
响应数据被编码为 Content-Type:application/json; charset=UTF-8
(我可以在我的浏览器网络选项卡中看到它)。
我哪里错了?我知道 $tags
里面有数据,因为我之前已经 var_dump
了。为什么它现在给出空输出?
基于documentation,你的操作应该是这样的:
public function ajaxTags()
{
$this->loadModel('Tag');
$tags = $this->Tag->find('list');
$this->set('tags', $tags);
$this->set('_serialize', array('tags'));
}
The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view.
您需要将变量 $tags
发送到视图,以便 _serialize
键能够识别并呈现它。