如何为JavaScript和JSON正确编码UTF-8? [英] How to properly encode UTF-8 for JavaScript and JSON?

查看:719
本文介绍了如何为JavaScript和JSON正确编码UTF-8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建输入验证哈希时遇到问题。 JavaScript将数据提交给API,API使用json_encode验证发送的数据。基本上它的工作方式如下:

I have a problem creating an input validation hash. JavaScript submits data to API and API validates the sent data with json_encode. Basically it works like this:

$input=array('name'='John Doe','city'=>'New York');
$validationHash=sha1(json_encode($input).$key); // Key is known to both servers

如果PHP连接到另一台服务器,那么一切正常。它也可以通过JavaScript工作(我也有自定义sha1()函数):

If PHP connects to another server, then everything works. It also works through JavaScript (I have a custom sha1() function there as well):

var validationHash = sha1(JSON.stringify({'name':'John Doe','city'=>'New York'})+ key);

var validationHash=sha1(JSON.stringify({'name':'John Doe','city'=>'New York'})+key);

当字符串包含UTF-8字符时,我的问题出现了。例如,如果其中一个值为:

My problem comes when the string contains UTF-8 characters. For example, if one of the values is:

Ränisipelgasöösel

接收命令的PHP服务器在JSON编码后将其转换为此值:

Then PHP server that receives the command converts it to this after JSON encoding:

R\u00e4nisipelgas\u00f6\u00f6sel

我需要在JavaScript中执行此操作好吧,但我还没弄清楚如何。我需要确保向服务器发送适当的验证哈希或命令失败。我从谷歌发现可以使用unescape(encodeURIComponent(string))和decodeURIComponent(),但是它们都没有给我与PHP有相同的字符串并验证。

I need to do this in JavaScript as well, but I haven't been able to work out how. I need to make sure that I send proper validation hash to the server or the command fails. I found from Google that unescape(encodeURIComponent(string)) and decodeURIComponent() could be used, but neither gives me the same string that PHP has and validates with.

UTF -8用于客户端和服务器。

UTF-8 is used on both client and server.

任何想法?

推荐答案

似乎不可能。我发现唯一可行的解​​决方案是在浏览器端使用encodeURIComponent()编码所有数据,在PHP端使用rawurlencode()编码,然后从数组中的这些值计算JSON。

It does not seem to be possible. The only working solution I have found is to encode all data with encodeURIComponent() on browser side and with rawurlencode() on PHP side and then calculate the JSON from these values in arrays.

这篇关于如何为JavaScript和JSON正确编码UTF-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆