如何在javascript内部进行base64编码 [英] How to base64 encode inside of javascript

查看:17
本文介绍了如何在javascript内部进行base64编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在网站上实现一个简单的脚本,该脚本将从谷歌的 ajax API 返回 base64 编码信息.这是我目前正在玩的:

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 编码,例如国家、地区、城市、纬度和经度.在 php 中它会很简单,但我无法弄清楚如何在 javascript 中做到这一点.任何帮助将不胜感激.

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() 函数分别用于 base 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() 不处理 ASCII 范围之外的 Unicode 字符.MDN 有 解决方法 但我可以为他们担保.感谢@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") );

这篇关于如何在javascript内部进行base64编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆