I want to produce a JSON response. I've tried the following in my Controller methods:
public function removeFilter($id = null)
{
$this->autoRender = false;
header('Content-Type: application/json');
echo json_encode(['result' => 'filter_removed']);
}
Then following instructions at CakePHP3.4: How to send a json object response? I also tried:
public function removeFilter($id = null)
{
$this->autoRender = false;
return $this->response
->withType('application/json')
->withStringBody(['result' => 'filter_removed']);
}
Both of these give a Response Headers of Content-Type: text/html; charset=UTF-8
Content-Type: text/html; charset=UTF-8
. There is no template associated with this Controller method, which is why autoRender = false
.
What's going wrong here?
CakePHP 3.5.13
Please try this. withStringBody
accepts a string only.
// If you want a json response
return $this->response->withType('application/json')
->withStringBody(json_encode(['result' => 'filter_removed']));
CakePHP More Info
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.