2010-09-23 12 views
20

Sto cercando di implementare un semplice script su un sito che restituirà informazioni codificate in base 64 dall'API di ajax di google. Questo è quello che sto giocando con finora:Come codificare base64 all'interno di 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> 

Esso restituisce informazioni che sto cercando di ottenere correttamente, ma ho bisogno di base64 codificare le parti separate, come paese, regione, città, lat e longitudine. In PHP sarebbe semplice, ma non riesco a capire come farlo in javascript. Qualsiasi aiuto sarebbe apprezzato.

+1

possibile duplicato di [Come è possibile codificare in Base64 utilizzando Javascript?] (Http://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript) –

risposta

15

This answer sembra corrispondere a quello che stai cercando.

C'è anche this one che è più elegante:

/** 
* 
* 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

Questo aspetto promettente, ma è un po 'fuori dalla mia profondità in javascript. Forse posso trovare un modo per fare tutto questo in PHP invece – Mike

+0

controllare i commenti [qui] (http://stackoverflow.com/a/246813/5090771) prima di usare ... – WhiteHat

20

Mozilla, WebKit e Opera hanno btoa() e atob() funzioni base 64 codifica e decodifica rispettivamente. Utilizzali laddove possibile perché saranno quasi certamente molto più veloci di un'implementazione JavaScript e ricadranno in uno dei tanti script che si presentano quando fai lo a web search.

MODIFICA 10 SETTEMBRE 2013: atob() e btoa() non gestiscono caratteri Unicode al di fuori dell'intervallo ASCII. MDN ha workarounds ma non posso garantire per loro. Grazie a @larspars per averlo indicato.

Ad esempio, se si sta utilizzando l'esempio di risposta di amphetamachine, si potrebbe procedere come segue:

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

Nota che atob e btoa non gestiranno unicode , mentre la risposta di @amphetamachine lo farà. Base64.encode ('☃') funziona, mentre btoa ('☃') genera un errore (testato in Firefox, Chrome e Opera) – larspars

+0

Dubitando ancora di usarlo, ma per ora penso che lo farò. Non abbiamo strani personaggi mentre lavoriamo con la lingua olandese. Grazie per aver pubblicato e modificato il tuo commento, questo ha aiutato molto nel decidere! ;) – ReSpawN

0

devo parte del codice della risposta qui:

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

e l'altra parte dalla risposta in questa pagina: https://stackoverflow.com/a/3776796/2655623

e qui è il risultato:

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); 
} 

Poiché questa cosa tenere in un posto, non voglio impegnarmi con il modo window.atb/window.btoa agire diversa in vari browser.

0

IE 10 & sopra e tutti i più recenti del browser

Encode String

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

Decodifica String

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

Oppure si potrebbe avere una propria funzione a pagina. small blog with references

Problemi correlati