简体   繁体   English

在URL中转义Base64字符串?

[英]Escape Base64 String in URL?

For some reason I need to put a Base64 encoded string in the URL, ie 由于某种原因,我需要在URL中放入Base64编码的字符串,即

<script>
    var URL = "localhost:8080/MyApp/order?z=AAAAAAAEJs4"
</script>

The URL is generated by Java, problem here is I can only use java to make the Base 64 encoded string to be URL friendly, but not javascript friendly, so fire bug give me the following error: URL是由Java生成的,这里的问题是我只能使用Java来使Base 64编码的字符串对URL友好,但对JavaScript不友好,因此,fire bug给我以下错误:

SyntaxError: unterminated string literal

Apparently there are charactors in the Base64 string requires escaping. 显然,Base64字符串中有字符需要转义。 However I cannot use escape() or URLencoding() method as the request will directly deliver to the controller and manipulated by java code, so there is no "next page" in this situation. 但是我不能使用escape()URLencoding()方法,因为该请求将直接传递到控制器并由Java代码操纵,因此在这种情况下没有“下一页”。

So how to make this work then? 那么如何使这项工作呢?

If your're trying to convert that z url attribute into an understandable string/variable, you have to use a library to convert that. 如果您尝试将z url属性转换为可以理解的字符串/变量,则必须使用库将其转换。 Below is a link to a base64 library for Javascript that you must load in. 以下是您必须加载的Javabase64库的链接。

http://www.webtoolkit.info/javascript-base64.html http://www.webtoolkit.info/javascript-base64.html

You maybe also need a library to access the z attribute in your url. 您可能还需要一个库来访问URL中的z属性。 I would recommend this: 我建议这样做:

https://github.com/allmarkedup/purl https://github.com/allmarkedup/purl

Just in case it helps, here is a short JS code requiring no dependency: 以防万一,这是一个简短的JS代码,不需要依赖:

String.prototype.base64EncodeUrl = function () {
    var str = this;
    str = window.btoa(unescape(encodeURIComponent( str )));
    return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
};

String.prototype.base64DecodeUrl = function () {
    var str = this, str_pad = (str + '===');
    str = str_pad.slice(0, str.length + (str.length % 4));
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    return decodeURIComponent(escape(window.atob( str )));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM