我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。
?search=%E6%F8%E5
URL参数的值,当解码时,应该是:
æøå
(人物是挪威人)。
我没有访问服务器的权限,所以我不能在上面修改任何东西。
我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。
?search=%E6%F8%E5
URL参数的值,当解码时,应该是:
æøå
(人物是挪威人)。
我没有访问服务器的权限,所以我不能在上面修改任何东西。
当前回答
@pauloppenheim对答案进行了轻微修改,因为它不能正确处理可能是其他参数名称的一部分的参数名称。
例如:如果你有“appenv”和“env”参数,重新处理“env”的值可以提取“appenv”值。
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
其他回答
根据999的回答:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
变化:
decodeURI()被decodeURIComponent()取代 (?|&]被添加在regexp的开头
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
需要添加参数i,使其不区分大小写:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
你不应该使用jQuery来做这样的事情! 现代的方法是通过包管理器(如Bower)使用小型可重用模块。
我创建了一个小模块,可以将查询字符串解析为对象。像这样使用它:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
这可能会有所帮助。
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>