我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。
?search=%E6%F8%E5
URL参数的值,当解码时,应该是:
æøå
(人物是挪威人)。
我没有访问服务器的权限,所以我不能在上面修改任何东西。
我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。
?search=%E6%F8%E5
URL参数的值,当解码时,应该是:
æøå
(人物是挪威人)。
我没有访问服务器的权限,所以我不能在上面修改任何东西。
当前回答
在阅读了所有的答案后,我最终得到了这个版本+第二个使用参数作为标志的函数
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
其他回答
如果你不知道URL参数是什么,并且想要获得一个包含参数中的键和值的对象,你可以使用这个:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
用类似/posts的url调用getParameters() ?日期=9/10/11&作者=nilbus将返回:
{
date: '9/10/11',
author: 'nilbus'
}
我不会在这里包括代码,因为它甚至远离问题,但weareon.net发布了一个库,允许操作URL中的参数:
博客:http://blog.weareon.net/working-with-url-parameters-in-javascript/ 代码:http://pastebin.ubuntu.com/1163515/
根据999的回答:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
变化:
decodeURI()被decodeURIComponent()取代 (?|&]被添加在regexp的开头
@pauloppenheim对答案进行了轻微修改,因为它不能正确处理可能是其他参数名称的一部分的参数名称。
例如:如果你有“appenv”和“env”参数,重新处理“env”的值可以提取“appenv”值。
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
在阅读了所有的答案后,我最终得到了这个版本+第二个使用参数作为标志的函数
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id)或getURLParameter(id)工作方式相同:)