如何为Base64 EN code的JavaScript内 [英] How to base64 encode inside of javascript
问题描述
我想实现的一个网站,将返回的base64途中从谷歌的AJAX API codeD信息一个简单的脚本。这是我迄今玩:
I am trying to implement a simple script on a site that will return base64 encoded information from google's ajax API. This is what I am playing with so far:
<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 EN code中的独立部分,如国家,地区,城市,纬度和经度。在PHP这将是简单,但我无法弄清楚如何做到这一点在JavaScript。任何帮助将是AP preciated。
It returns the info I am trying to get properly, but I need to base64 encode the separate parts such as country, region, city, lat and longitude. In php it would be simple, but I cannot figure out how to do it in javascript. Any help would be appreciated.
推荐答案
的Mozilla,WebKit和Opera都拥有 BTOA()
和 ATOB ()
分别为64基编码和解码功能。使用那些可能的,因为他们几乎肯定会大量快于JavaScript的执行情况,并回落到当你做的网络搜索。
Mozilla, WebKit and Opera all have btoa()
and atob()
functions for base 64 encoding and decoding respectively. Use those where possible because they will almost certainly be massively faster than a JavaScript implementation and fall back to one of the many scripts that turn up when you do a web search.
修改2013年9月10日: ATOB()
和 BTOA()
不处理的Uni $ C ASCII范围之外的$ C字符。 MDN有<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding#The_.22Uni$c$c_Problem.22\">workarounds但我不能为他们提供担保。感谢@larspars指出了这一点。
EDIT 10 SEPTEMBER 2013: atob()
and btoa()
do not handle Unicode characters outside the ASCII range. MDN has workarounds but I can't vouch for them. Thanks to @larspars for pointing this out.
例如,如果你使用的amphetamachine的答案例如,你可以做到以下几点:
For example, if you were using the example from amphetamachine's answer, you could do the following:
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") );
这篇关于如何为Base64 EN code的JavaScript内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!