简体   繁体   English

JavaScript JSON.parse UTF-8问题

[英]JavaScript JSON.parse UTF-8 problems

I have a page that makes a request to a php file via AJAX, and that AJAX file displays a JSON which is the response, and I've got some issues with it. 我有一个页面,它通过AJAX向php文件发出请求,并且该AJAX文件显示了一个JSON(即响应),但我遇到了一些问题。

It results that my page uses UTF-8 charset in order to display some special chars, etc; 结果是我的页面使用UTF-8字符集来显示某些特殊字符等。 my AJAX file used ANSI encoding by default but then I decided to change it to UTF-8 to get the correct symbols with it too, but when I use JSON.parse it throws me the error "Uncaught SyntaxError: Unexpected token", (if the AJAX file is encoded as UTF-8), then I change to ANSI and it works great, I don't know why JSON has that behaviour. 我的AJAX文件默认情况下使用ANSI编码,但是后来我决定将其更改为UTF-8以获取正确的符号,但是当我使用JSON.parse时,它抛出错误“ Uncaught SyntaxError:Unexpected token”,(如果(将AJAX文件编码为UTF-8),然后更改为ANSI,效果很好,我不知道为什么JSON具有这种行为。

When I look at the output (xhr.responseText) both from ANSI and UTF-8 are identical (I'm not even using special chars in UTF-8). 当我查看ANSI和UTF-8的输出(xhr.responseText)时,它们是相同的(我什至没有在UTF-8中使用特殊字符)。

Maybe JSON.parse doesn't accept response from UTF-8 files (something that I don't believe) or do I have to set a header in order to fix that? 也许JSON.parse不接受来自UTF-8文件的响应(我不相信这一点),或者我必须设置标头来解决此问题? What do you guys think about it? 你们怎么看? Thank you.. 谢谢..

I had faced same problem. 我曾经遇到过同样的问题。 I used following encode functions instead of default encode function. 我使用以下编码功能代替默认编码功能。 It gives me perfect result 它给我完美的结果

function json_encode_utf8($arr) {
  array_walk_recursive($arr, 'encode_utf8');
  return mb_decode_numericentity(json_encode($arr), array(0x80, 0xffff, 0, 0xffff), 'UTF-8');
}

function encode_utf8(&$item, $key) {
  if (is_string($item))
    $item = mb_encode_numericentity($item, array(0x80, 0xffff, 0, 0xffff), 'UTF-8');
}

$group_members = array('Matthias  Schöbe');

$group_members_json = json_encode_utf8($group_members);

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

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