【发布时间】:2017-11-10 14:27:24
【问题描述】:
我有一个 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' 数据库表中的 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 输出它,如文档中所述。我不需要“视图”,因为我不想做任何额外的格式化:
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'd 它。为什么现在输出空?
【问题讨论】:
-
尝试把
$this->set('_serialize', array($tags));替换成$this->set('tags', $tags); $this->set('_serialize', array('tags')); -
@SamHecquet 是的,这行得通。但为什么?谢谢。
-
我编辑了我的答案来解释为什么你需要设置这个变量
标签: php json cakephp cakephp-2.0