[英]Set Content-Type header in CakePHP with JSON
I need to set Content-Type: application/json; charset=UTF-8
我需要设置
Content-Type: application/json; charset=UTF-8
Content-Type: application/json; charset=UTF-8
in a data view from CakePHP.来自 CakePHP 的数据视图中的
Content-Type: application/json; charset=UTF-8
。 I've already tried to set $this->response->header('Content-Type', 'application/json; charset=UTF-8');
我已经尝试设置
$this->response->header('Content-Type', 'application/json; charset=UTF-8');
but that doesn't change anything.但这不会改变任何事情。 It still just output
Content-Type: application/json
.它仍然只是输出
Content-Type: application/json
。
its in the code (CakeResponse, line 447):它在代码中(CakeResponse,第 447 行):
if (strpos($this->_contentType, 'text/') === 0) {
$this->header('Content-Type', "{$this->_contentType}; charset={$this->_charset}");
} else {
$this->header('Content-Type', "{$this->_contentType}");
}
so only for "text/..." the charset will be appended.所以只有“text/...”字符集才会被附加。 I dont know why, though...
我不知道为什么,虽然...
Funny, I had this same problem just last night.有趣的是,我昨晚也遇到了同样的问题。 It seems that UTF-8 is the default JSON encoding and that's probably why the header isn't sent by Cake (but I couldn't find reference to this decision either way).
似乎 UTF-8 是默认的 JSON 编码,这可能就是 Cake 不发送标头的原因(但无论如何我都找不到对这个决定的引用)。
Solution for me was to use a php's json_decode()
-- it should decode the string properly.我的解决方案是使用 php 的
json_decode()
- 它应该正确解码字符串。 I had lots of French accents showing up as java/C unicode, eg \é
and thought it was a header problem.我有很多法语口音显示为 java/C unicode,例如
\é
并认为这是一个标题问题。 But after running the string through json_decode()
the accented characters all showed correctly.但是在通过
json_decode()
运行字符串后,重音字符全部正确显示。
Marks' link the comments has good info too. Marks 的链接评论也有很好的信息。
for this you can place this in the controller / function:为此,您可以将其放在控制器/函数中:
json_encode($updown_rs);
and in the view file (views/check_json):并在视图文件(views/check_json)中:
var json_object = $.parseJSON(response);
application/json doesn't have a charset parameter. application/json 没有字符集参数。 There's no point in trying to set one.
试图设置一个是没有意义的。 See http://rfc7159.net/rfc7159#ianacons .
请参阅http://rfc7159.net/rfc7159#ianacons 。
我正在使用 cake 2.10.11 并在 json 布局中使用了此代码:
$this->response->charset('utf-8');
You can do it by using $this->RequestHandler->ext = 'json';
你可以通过使用
$this->RequestHandler->ext = 'json';
in your beforefilter method在你的 beforefilter 方法中
check out the following example看看下面的例子
public function beforeFilter(){
parent::beforeFilter();
$this->RequestHandler->ext = 'json';
}
public function index()
{
$this->autoRender = false;
$output = array(
array('value' =>'first value'),
array('value' =>'second value'),
);
$json = json_encode($output);
$this->response->body($json);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.