简体   繁体   English

使用Java脚本删除Base64编码的URL参数

[英]Strip Base64-encoded URL parameters with Javascript

I'm decoding my URL parameters in .NET as explained in this article . 在解释我在.NET解码我的URL参数这篇文章 In some cases I need to get the URL parameters in Javascript. 在某些情况下,我需要获取Javascript中的URL参数。 But the problem is that some parameter values end at a '='. 但是问题在于某些参数值以'='结尾。

Example: ?itemID=Jj1TI9KmB74=&cat=1 示例: ?itemID = Jj1TI9KmB74 =&cat = 1

Javascript function: JavaScript函数:

function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

for (var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}

return vars;}

I know my problem is at the split-function in the for-loop but I don't know how to solve it. 我知道我的问题出在for循环的split函数中,但我不知道如何解决。 I also used jsuri for this but the problem still exists. 我也为此使用jsuri ,但问题仍然存在。 Can I solve this in Javascript or do I need to reconsider my encryption-method? 我可以用Javascript解决这个问题还是需要重新考虑我的加密方法?

Having an unencoded = in the URL is invalid. URL中的未编码=无效。 To do this right, you would have to additionally apply encodeURIComponent() on the base64 encoded data. 为此,您必须在base64编码数据上另外应用encodeURIComponent()

Whether the base64 encoding still makes sense then, is for you to decide. 那么,base64编码是否仍然有意义,将由您决定。

Reference: RFC 3986: Reserved characters 参考: RFC 3986:保留字符

Having = unencoded in the URI query is invalid. URI查询中的=未编码无效。 You should escape it. 你应该逃避它。 However, for completeness, if you really needed to do this, try this: 但是,出于完整性考虑,如果您确实需要执行此操作,请尝试以下操作:

Extra note: if you escaped the = using URI encoding, on the server side (eg $_GET) it'll be automatically decoded. 附加说明:如果使用URI编码转义了= ,则在服务器端(例如$ _GET)将自动对其进行解码。 With JavaScript and location , however, you must decode it first ( decodeURIComponent ) to work with it. 但是,使用JavaScript和location时,必须先对其进行解码( decodeURIComponent )才能使用它。

Instead of doing: 而不是做:

hash = hashes[i].split('=');

where subsequent equals signs are split too, do this instead (a non-greedy match before the first equals symbol for the key name, the rest for the value): 如果后续的等号也被拆分,请改为这样做(键名的第一个等号之前为非贪婪匹配,其余为值):

match = hashes[i].match(/([^=]+?)=(.+)/);
key = match[1];
value = match[2];

I assume you can't control the process generating the =s? 我假设您无法控制生成= s的过程? As Pekka said it's wrong. 正如Pekka所说的那样。

However you could manually break the string at the first =, eg 但是,您可以在第一个=处手动断开字符串,例如

var i = hashes[i].indexof('=');
if (i > 0)
{
    var key = hashes[i].substring(0,i);
    vars.push(key);
    if ((i+1) < hashes[i].length)
    {
        vars[key] = hashes[i].substring(i+1);
    }
}
else
{
    // No value
    vars.push(hashes[i]);
}

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

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