[英]Encoding special characters to Base64 in Javascript and decoding using base64_decode() in PHP
My problem is that the base64_decode() function does not work with special characters. 我的问题是base64_decode()函数不适用于特殊字符。 Maybe the problem is that I am using an ajax event and I am parsing the data using base64.encode from javascript.
也许问题是我正在使用ajax事件,我正在使用javascript中的base64.encode解析数据。 js code:
js代码:
description: $.base64.encode($("#Contact_description").val())
and this is the php code: 这是PHP代码:
$model->description = base64_decode($model->description);
where $model->description
is the $("#Contact_description").val()
value 其中
$model->description
是$("#Contact_description").val()
值
Example this is the description value : Traian Băsescu and this is how I look after using the decode from php : Traian A sescu . 示例这是描述值: TraianBăsescu ,这就是我在使用php解码后的方式: TraianA sescu 。 What should I do ?
我该怎么办 ?
UPDATE: This the header information from firebug: 更新:这是来自firebug的标题信息:
Content-Length 143
Content-Type text/html; **charset=UTF-8**
Date Fri, 20 Mar 2015 12:37:01 GMT
The following works for me: 以下适用于我:
JavaScript: JavaScript的:
// Traian Băsescu encodes to VHJhaWFuIELEg3Nlc2N1
var base64 = btoa(unescape(encodeURIComponent( $("#Contact_description").val() )));
PHP: PHP:
$utf8 = base64_decode($base64);
The problem is that Javascript strings are encoded in UTF-16, and browsers do not offer very many good tools to deal with encodings. 问题是Javascript字符串是用UTF-16编码的,而浏览器并没有提供很多很好的工具来处理编码。 A great resource specifically for dealing with Base64 encodings and Unicode can be found at MDN: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
可以在MDN上找到专门用于处理Base64编码和Unicode的优秀资源: https : //developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
Their suggested solution for encoding strings without using the often cited solution involving the deprecated unescape
function is: 他们建议的编码字符串的解决方案, 而不使用经常引用的涉及弃用的
unescape
函数的解决方案是:
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
For further solutions and details I highly recommend you read the entire page. 有关更多解决方案和详细信息,我强烈建议您阅读整个页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.