【问题标题】:How do you send a JSON response in CakePHP 3.x如何在 CakePHP 3.x 中发送 JSON 响应
【发布时间】: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


【解决方案1】:

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

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

CakePHP More Info

【讨论】:

  • 什么是$response??这没有定义,所以不会起作用。
  • 它将是 Cake\Http\Response 的一个对象。我已经编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多