我正在寻找一个jQuery插件,可以获得URL参数,并支持这个搜索字符串而不输出JavaScript错误:“畸形的URI序列”。如果没有jQuery插件支持这一点,我需要知道如何修改它来支持这一点。

?search=%E6%F8%E5

URL参数的值,当解码时,应该是:

æøå

(人物是挪威人)。

我没有访问服务器的权限,所以我不能在上面修改任何东西。


当前回答

以下是我从这里的评论中创建的内容,以及修复没有提到的错误(例如实际返回null,而不是'null'):

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

其他回答

我创建了一个简单的函数,从JavaScript的URL中获取URL参数,如下所示:

.....58e/web/viewer.html?page=*17*&getinfo=33


function buildLinkb(param) {
    var val = document.URL;
    var url = val.substr(val.indexOf(param))  
    var n=parseInt(url.replace(param+"=",""));
    alert(n+1); 
}
buildLinkb("page");

输出:18

你不应该使用jQuery来做这样的事情! 现代的方法是通过包管理器(如Bower)使用小型可重用模块。

我创建了一个小模块,可以将查询字符串解析为对象。像这样使用它:

// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå

以下是我从这里的评论中创建的内容,以及修复没有提到的错误(例如实际返回null,而不是'null'):

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

@pauloppenheim对答案进行了轻微修改,因为它不能正确处理可能是其他参数名称的一部分的参数名称。

例如:如果你有“appenv”和“env”参数,重新处理“env”的值可以提取“appenv”值。

Fix:

var urlParamVal = function (name) {
    var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
    return result ? decodeURIComponent(result[2]) : "";
};
$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href); 
  return (results !== null) ? results[1] : 0;
}

$.urlParam("key");