【发布时间】:2018-12-12 15:21:38
【问题描述】:
我想生成一个 JSON 响应。我在 Controller 方法中尝试了以下方法:
public function removeFilter($id = null)
{
$this->autoRender = false;
header('Content-Type: application/json');
echo json_encode(['result' => 'filter_removed']);
}
然后按照CakePHP3.4: How to send a json object response?的说明我也试过了:
public function removeFilter($id = null)
{
$this->autoRender = false;
return $this->response
->withType('application/json')
->withStringBody(['result' => 'filter_removed']);
}
这两个都给出了Content-Type: text/html; charset=UTF-8 的响应标头。没有与此 Controller 方法关联的模板,这就是 autoRender = false 的原因。
这里出了什么问题?
CakePHP 3.5.13
【问题讨论】:
-
最简单、最干净的方法是在您的 URL 中使用 .json 扩展名。请参阅this sandbox example 背后的代码。
标签: php cakephp cakephp-3.0