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

?search=%E6%F8%E5

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

æøå

(人物是挪威人)。

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


当前回答

您可以使用浏览器本机位置。搜索属性:

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return unescape(val[1]);
    }
  }
  return null;
}

但是有一些jQuery插件可以帮助你:

查询对象 getURLParam

其他回答

需要添加参数i,使其不区分大小写:

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
    );
  }

根据999的回答:

function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );  
}

变化:

decodeURI()被decodeURIComponent()取代 (?|&]被添加在regexp的开头

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

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

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

Fix:

var urlParamVal = function (name) {
    var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
    return result ? decodeURIComponent(result[2]) : "";
};

例如,返回任意参数变量值的函数。

function GetURLParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

这就是你如何使用这个函数假设URL是,

“http://example.com/?technology=jquery&blog=jquerybyexample”。

var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');

所以在上面的代码变量"tech"将有"jQuery"作为值和"blog"变量的将是" querybyexample"。