php - CakePHP 2.x 不生成 json 响应

标签 php json cakephp cakephp-2.0

我有一个 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/

相关文章:

php - 在 PHP 和 Android 中将时间戳转换为可读时间

html - CakePhp-Bootstrap 提交按钮不会与文本框对齐

php - CakePHP 在不破坏 Cake 自动化的情况下自行加入 HABTM 表

php - 这段代码是什么意思 : `$Odd = ($Odd == "even") ? "odd": "even";` ?

javascript - 为什么当我单击按钮时会加载我们的页面

json - 如何将 JSON 解码为 pandas 数据帧?

CakePHP 可包含条件不限制结果?

php - 术语突出显示算法 (HTML)

javascript - 未捕获的类型错误 : action. 序列化不是函数

php - JSON 常量表示它们在 Ubuntu 上的 PHP 5.5 中未定义