我在解析 JavaScript 中的 URL 编码查询字符串参数时遇到了一个奇怪的问题。
function getUrlVars() {
var vars = [], hash;
alert(window.location.href);
var hashes = window.location.href.slice(decodeURIComponent(window.location.href).indexOf('?') + 1).split('&');
alert(decodeURIComponent(window.location.href));
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
网址:http://domain/approveFile/ApproveFile.aspx?id=DZj9aEoyZ2I%3d
值"DZj9aEoyZ2I="
是一个base64 URL编码值,但它不能正确解析;它忽略“%3d”
。请提出解决方案?
最佳答案
您在拆分 =
之前对各部分进行解码,这意味着 %3d
被视为键值分隔符,结束位于循环内的 hash[2]
中。这似乎是不受欢迎的行为,因此解决方法是在所有 .split
s
decodeURIComponent
<小时/>
尝试将 foo[]
实现为列表功能,类似于您在 php 中找到的功能,发帖以求繁荣..
function getUrlVars() {
var $_GET = Object.create(null), // for..in safe
pairs = window.location.search.slice(1).split('&'),
pair,
i;
for (i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
if (pair[0].slice(-2) === '[]') {
pair[0] = pair[0].slice(0, -2);
pair[0] = decodeURIComponent(pair[0]);
if (pair[1]) pair[1] = decodeURIComponent(pair[1]); // don't assume this
if (!(pair[0] in $_GET))
$_GET[pair[0]] = [];
else if (!Array.isArray($_GET[pair[0]]))
$_GET[pair[0]] = [$_GET[pair[0]]];
$_GET[pair[0]].push(pair[1]);
} else {
pair[0] = decodeURIComponent(pair[0]);
if (pair[1]) pair[1] = decodeURIComponent(pair[1]); // don't assume this
$_GET[pair[0]] = pair[1];
}
}
return $_GET;
}
在URL上使用搜索 ?foo=bar%3d&baz[]=fizz&baz[]=buzz
将给出
getUrlVars(); // {"foo": "bar=", "baz": ["fizz", "buzz"]}
关于JavaScript 解析 urlencoded 查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131161/