简体   繁体   English

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

[英]How do you send a JSON response in CakePHP 3.x

I want to produce a JSON response. 我想产生一个JSON响应。 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? 然后按照CakePHP3.4上的说明进行操作:如何发送json对象响应? 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的响应头Content-Type: text/html; charset=UTF-8 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 . 没有与此Controller方法关联的模板,这就是为什么autoRender = false

What's going wrong here? 这是怎么了

CakePHP 3.5.13 CakePHP 3.5.13

Please try this. 请尝试这个。 withStringBody accepts a string only. withStringBody仅接受字符串。

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

CakePHP More Info CakePHP 更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM