簡體   English   中英

在Javascript中將特殊字符編碼到Base64並使用PHP中的base64_decode()進行解碼

[英]Encoding special characters to Base64 in Javascript and decoding using base64_decode() in PHP

我的問題是base64_decode()函數不適用於特殊字符。 也許問題是我正在使用ajax事件,我正在使用javascript中的base64.encode解析數據。 js代碼:

description: $.base64.encode($("#Contact_description").val())

這是PHP代碼:

$model->description = base64_decode($model->description);

其中$model->description$("#Contact_description").val()

示例這是描述值: TraianBăsescu ,這就是我在使用php解碼后的方式: TraianA sescu 我該怎么辦 ?

更新:這是來自firebug的標題信息:

Content-Length  143
Content-Type    text/html; **charset=UTF-8**
Date    Fri, 20 Mar 2015 12:37:01 GMT

以下適用於我:

JavaScript的:

// Traian Băsescu encodes to VHJhaWFuIELEg3Nlc2N1
var base64 = btoa(unescape(encodeURIComponent( $("#Contact_description").val() )));

PHP:

$utf8 = base64_decode($base64);

問題是Javascript字符串是用UTF-16編碼的,而瀏覽器並沒有提供很多很好的工具來處理編碼。 可以在MDN上找到專門用於處理Base64編碼和Unicode的優秀資源: https//developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

他們建議的編碼字符串的解決方案, 而不使用經常引用的涉及棄用的unescape函數的解決方案是:

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

有關更多解決方案和詳細信息,我強烈建議您閱讀整個頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM