我有一个 Cake 2.x 应用程序。我需要从 PHP 数组提供 JSON 编码响应,但它没有按预期工作。
在 app/Config/routes.php
中,我有 Router::parseExtensions('json');
在我的 Controller 中,我有以下代码:
public function ajaxTags()
{
$this->loadModel('Tag');
$tags = $this->Tag->find('list');
var_dump($tags);
die;
}
这会产生我所期望的结果 - 我的 'tags'
数据库表中的 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));
}
这给出了以下响应:
空
响应数据编码为Content-Type:application/json; charset=UTF-8
(我可以在浏览器的“网络”选项卡中看到它)。
我哪里出错了?我知道 $tags
中有数据,因为我之前 var_dump
已经得到了它。为什么现在输出为空?
最佳答案
基于documentation ,你的 Action 应该是这样的:
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
发送到 View ,以便 _serialize
键知道它并渲染它。
关于php - CakePHP 2.x 不生成 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47224969/