你如何在 CakePHP 3.x 中发送 JSON 响应

And*_*ndy 0 php cakephp cakephp-3.0

我想生成一个 JSON 响应。我在我的控制器方法中尝试了以下方法:

public function removeFilter($id = null)
{
    $this->autoRender = false;

    header('Content-Type: application/json');
    echo json_encode(['result' => 'filter_removed']);
}
Run Code Online (Sandbox Code Playgroud)

然后按照CakePHP3.4 中的说明进行操作:如何发送 json 对象响应?我也试过:

public function removeFilter($id = null)
{
    $this->autoRender = false;

    return $this->response
    ->withType('application/json')
    ->withStringBody(['result' => 'filter_removed']);
}
Run Code Online (Sandbox Code Playgroud)

这两个都给出了Content-Type: text/html; charset=UTF-8. 没有与此 Controller 方法关联的模板,这就是为什么autoRender = false.

这里出了什么问题?

蛋糕PHP 3.5.13

Rak*_*tra 6

请试试这个。withStringBody只接受一个字符串。

// If you want a json response
return $this->response->withType('application/json')
    ->withStringBody(json_encode(['result' => 'filter_removed']));
Run Code Online (Sandbox Code Playgroud)

CakePHP更多信息