[英]Decoding not working with Base64
编码我的URL可以与base-64编码完美结合。 解码也是如此,但不能使用字符串文字变量 。
这有效:
document.write(atob("hi"));
这不是:
var tempvar = "hello";
document.write(atob(tempvar));
我究竟做错了什么? 什么都没有显示。 但是,如果我引用"tempvar"
,那么它当然可以工作,但由于"tempvar"
是字符串而不是变量,所以不是同一回事。
这是因为它无法解码字符串"hello"
,请尝试可以从base64解码的实际字符串。
var tempvar = "aHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy80MzEyOTEzNi9kZWNvZGluZy1ub3Qtd29ya2luZy13aXRoLWJhc2U2NA==";
document.write(atob(tempvar));
如果要编码,请改用btoa
函数,
var tempvar = "hello";
document.write(btoa(tempvar));
您可以使用此网站来测试对base64的解码和编码, https: //www.base64encode.org/
我究竟做错了什么?
传递给atob()的字符串是长度为5的字符串文字(从技术上讲,不是基数为64的编码字符串)。 浏览器控制台应在错误日志中显示异常(请参见下面的原因中的说明)。
根据atob()的MDN文档:
投掷
抛出一个抛出:DOMException如果传入的字符串的长度不是4的倍数1
字符串文字“ hello ”的长度(即5 )不是4的倍数。因此,抛出异常,而不是返回字符串文字的解码版本。
一种解决方案是使用实际上已编码的字符串(例如,使用btoa() )或至少具有四个长度(例如,使用String.prototype.substring() )。 有关示例,请参见下面的代码段。
var tempvar = "hello"; window.addEventListener("DOMContentLoaded", function(readyEvent) { var container = document.getElementById("container"); //encode the string var encoded = btoa(tempvar); container.innerHTML = encoded; var container2 = document.getElementById("container2"); //decode the encoded string container2.innerHTML = atob(encoded); var container3 = document.getElementById("container3"); //decode the first 4 characters of the string container3.innerHTML = atob(tempvar.substring(0, 4)); });
<div> btoa(tempvar): <span id="container"></span></div> <div> atob(decoded): <span id="container2"></span></div> <div> atob(tempvar.substring(0, 4)): <span id="container3"></span></div>
1 https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/atob
这是因为您正在尝试解码在hi上工作的不是base64编码的字符串,这似乎只是一个巧合。
atob =解码
btoa =编码
您使用了错误的功能。 您应该使用btoa()
进行编码。
当您执行atob('hi')
,实际上是在解码'hi',它恰好是有效的base-64。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.