2010-09-23 36 views
20

我想在一個網站上實現一個簡單的腳本,它會從google的ajax API返回base64編碼的信息。這是我與迄今玩:如何base64編碼在javascript裏面

<html> 
<head> 
<script src="http://www.google.com/jsapi?key=ABQIAAAA0duujonFsEX871htGWZBHRS76H0qhS7Lb-D1Gd0Mnaiuid8Z7BQIyz2kMpojKizoyiCQA4yRkKAKug" type="text/javascript"></script> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/javascript"> 
    jQuery(document).ready(function() { 
    var location = 'Unable to determine your location.'; 
    if (google.loader.ClientLocation) { 
     var loc = google.loader.ClientLocation; 
     location = 'Country: <strong>' + loc.address.country + '</strong>, Region: <strong>' + loc.address.region + '</strong>, City: <strong>' + 
       loc.address.city + '</strong>, Lat/Long: <strong>' + loc.latitude + ', ' + loc.longitude + '</strong>'; 
    } 
    jQuery('.geolocation').html(location); 
    }); 
</script> 
</head> 
<body> 
<span class="geolocation"></span> 
</body> 
</html> 

它返回我試圖得到正確的信息,但我需要Base64編碼,獨立的部分,如國家,地區,城市,緯度和經度。在PHP中它會很簡單,但我不知道如何在JavaScript中做到這一點。任何幫助,將不勝感激。

+1

可能的重複[你如何使用Javascript編碼到Base64?](http://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript) – 2010-09-23 09:04:05

回答

15

This answer似乎符合你要找的東西。

還有this one哪個更優雅:

/** 
* 
* Base64 encode/decode 
* http://www.webtoolkit.info/ 
* 
**/ 

var Base64 = { 

    // private property 
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/=", 

    // public method for encoding 
    encode : function (input) { 
     var output = ""; 
     var chr1, chr2, chr3, enc1, enc2, enc3, enc4; 
     var i = 0; 

     input = Base64._utf8_encode(input); 

     while (i < input.length) { 

      chr1 = input.charCodeAt(i++); 
      chr2 = input.charCodeAt(i++); 
      chr3 = input.charCodeAt(i++); 

      enc1 = chr1 >> 2; 
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 
      enc4 = chr3 & 63; 

      if (isNaN(chr2)) { 
       enc3 = enc4 = 64; 
      } else if (isNaN(chr3)) { 
       enc4 = 64; 
      } 

      output = output + 
      this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + 
      this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); 

     } 

     return output; 
    }, 

    // public method for decoding 
    decode : function (input) { 
     var output = ""; 
     var chr1, chr2, chr3; 
     var enc1, enc2, enc3, enc4; 
     var i = 0; 

     input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); 

     while (i < input.length) { 

      enc1 = this._keyStr.indexOf(input.charAt(i++)); 
      enc2 = this._keyStr.indexOf(input.charAt(i++)); 
      enc3 = this._keyStr.indexOf(input.charAt(i++)); 
      enc4 = this._keyStr.indexOf(input.charAt(i++)); 

      chr1 = (enc1 << 2) | (enc2 >> 4); 
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); 
      chr3 = ((enc3 & 3) << 6) | enc4; 

      output = output + String.fromCharCode(chr1); 

      if (enc3 != 64) { 
       output = output + String.fromCharCode(chr2); 
      } 
      if (enc4 != 64) { 
       output = output + String.fromCharCode(chr3); 
      } 

     } 

     output = Base64._utf8_decode(output); 

     return output; 

    }, 

    // private method for UTF-8 encoding 
    _utf8_encode : function (string) { 
     string = string.replace(/\r\n/g,"\n"); 
     var utftext = ""; 

     for (var n = 0; n < string.length; n++) { 

      var c = string.charCodeAt(n); 

      if (c < 128) { 
       utftext += String.fromCharCode(c); 
      } 
      else if((c > 127) && (c < 2048)) { 
       utftext += String.fromCharCode((c >> 6) | 192); 
       utftext += String.fromCharCode((c & 63) | 128); 
      } 
      else { 
       utftext += String.fromCharCode((c >> 12) | 224); 
       utftext += String.fromCharCode(((c >> 6) & 63) | 128); 
       utftext += String.fromCharCode((c & 63) | 128); 
      } 

     } 

     return utftext; 
    }, 

    // private method for UTF-8 decoding 
    _utf8_decode : function (utftext) { 
     var string = ""; 
     var i = 0; 
     var c = c1 = c2 = 0; 

     while (i < utftext.length) { 

      c = utftext.charCodeAt(i); 

      if (c < 128) { 
       string += String.fromCharCode(c); 
       i++; 
      } 
      else if((c > 191) && (c < 224)) { 
       c2 = utftext.charCodeAt(i+1); 
       string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); 
       i += 2; 
      } 
      else { 
       c2 = utftext.charCodeAt(i+1); 
       c3 = utftext.charCodeAt(i+2); 
       string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); 
       i += 3; 
      } 

     } 

     return string; 
    } 

} 
+0

這看起來很像很有前途,但它在javascript中有點超出我的深度。也許我可以找到一種方法來做所有這些在PHP而不是 – Mike 2010-09-23 01:02:15

+0

檢查評論[這裏](http://stackoverflow.com/a/246813/5090771)之前... – WhiteHat 2016-02-09 14:41:56

20

Mozilla中,WebKit和Opera都具有用於分別底座64的編碼和解碼btoa()atob()功能。儘可能使用這些內容,因爲它們幾乎可以肯定比JavaScript實現更快速,並且可以回溯到當您執行a web search時出現的許多腳本之一。

編輯2013年9月10日:atob()btoa()不處理ASCII範圍以外的Unicode字符。 MDN有workarounds,但我不能爲他們擔保。感謝@larspars指出了這一點。

例如,如果您正在使用從amphetamachine的答案例如,你可以做到以下幾點:

if (!window.btoa) { 
    window.btoa = function(str) { 
     return Base64.encode(str); 
    } 
} 

if (!window.atob) { 
    window.atob = function(str) { 
     return Base64.decode(str); 
    } 
} 

alert(btoa("Some text")); 
+1

請注意,atob和btoa不會處理unicode ,而@ amphetamachine的答案會。 Base64編碼。編碼('☃')的作品,而btoa('☃')拋出一個錯誤(在Firefox,Chrome和Opera中測試) – larspars 2013-09-10 07:56:14

+0

仍然懷疑是否使用它,但現在我想我會。我們在使用荷蘭語的時候沒有奇怪的字符。感謝您發佈並編輯您的評論,這對決定有很大幫助! ;) – ReSpawN 2013-12-11 09:04:33

0

我的代碼的一部分,從答案在這裏:

https://scotch.io/quick-tips/how-to-encode-and-decode-strings-with-base64-in-javascript

和本頁回答的其他部分: https://stackoverflow.com/a/3776796/2655623

這裏是結果:

var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}} 

window.btoa = function(str) { 
    return Base64.encode(str); 
} 

window.atob = function(str) { 
    return Base64.decode(str); 
} 

如在一個地方這讓一切,我不會怎麼window.atb/window.btoa採取行動,不同的瀏覽器不同的涉及自己。

0

IE 10 &以上,所有最新的瀏覽器

編碼字符串

var str = "raj"; 
var enc = window.btoa(str); // cmFq 

解碼字符串

var dec = window.atoa('cmFq'); // raj 

否則你可能有頁面上自己的函數。 small blog with references