【发布时间】:2012-02-29 19:07:34
【问题描述】:
我按照this tutorial 为 JSON 和 XML 设置了我的 REST Web 服务。 XML 输出正确,但是当我进行 JSON 调用时,我从 Cake 中得到视图未找到显示。
为此,我在 AppController 中添加了以下代码:
if ( $this->RequestHandler->isAjax() ) {
//Configure::write ( 'debug', 0 );
$this->layout = 'ajax';
$this->autoRender = false;
} elseif ($this->RequestHandler->isXml()) {
$this->layout = 'default';
//Configure::write ( 'debug', 0 );
} elseif ($this->RequestHandler->ext == 'json') {
$this->RequestHandler->setContent('json','text/x-json');
$this->layout = 'default';
} elseif ($this->RequestHandler->accepts('html')) {
$this->layout = 'frontend';
}
这是我的控制器方法之一中的代码示例:
if ($this->RequestHandler->isXml()) {
$voicenote = $voicenote['Voicenote'];
$this->set(compact('voicenote'));
} else if ($this->RequestHandler->ext == 'json') {
$voicenote = $voicenote['Voicenote'];
pr($voicenote);
echo json_encode(array('voicenote' => $voicenote));
} else {
$this->set(compact('voicenote', 'tiny_list'));
}
XML 显示正常,只是 JSON 是问题所在。
【问题讨论】:
-
您是使用 AJAX 请求测试 json,还是只是在浏览器中输入 URL?
-
只是 URL,我得到的视图没有找到 CakePHP 默认视图,但我知道它正在通过正确的渠道,因为我打印出调用的结果,我可以看到 JSON 数组
-
JSON 显示不正确怎么办?
application/json是 JSON 的标准内容类型,而不是text/x-json。
标签: xml json cakephp rest cakephp-1.3