如何在 CakePHP 3.x 中发送 JSON 响应
How do you send a JSON response in CakePHP 3.x
我想生成 JSON 响应。我在我的控制器方法中尝试了以下方法:
public function removeFilter($id = null)
{
$this->autoRender = false;
header('Content-Type: application/json');
echo json_encode(['result' => 'filter_removed']);
}
然后按照 的说明进行操作 我也尝试了:
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
的响应 Headers。没有与此 Controller 方法关联的模板,这就是 autoRender = false
.
的原因
这里出了什么问题?
CakePHP 3.5.13
请试试这个。 withStringBody
只接受字符串。
// If you want a json response
return $this->response->withType('application/json')
->withStringBody(json_encode(['result' => 'filter_removed']));
CakePHP More Info
我想生成 JSON 响应。我在我的控制器方法中尝试了以下方法:
public function removeFilter($id = null)
{
$this->autoRender = false;
header('Content-Type: application/json');
echo json_encode(['result' => 'filter_removed']);
}
然后按照
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
的响应 Headers。没有与此 Controller 方法关联的模板,这就是 autoRender = false
.
这里出了什么问题?
CakePHP 3.5.13
请试试这个。 withStringBody
只接受字符串。
// If you want a json response
return $this->response->withType('application/json')
->withStringBody(json_encode(['result' => 'filter_removed']));
CakePHP More Info