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

?search=%E6%F8%E5

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

æøå

(人物是挪威人)。

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


当前回答

<script type="text/javascript">
function getURLParameter(name) {
        return decodeURIComponent(
            (location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
        );
    }

</script>

getURLParameter(id)或getURLParameter(id)工作方式相同:)

其他回答

以防你们有localhost/index。xsp这样的url ?A =1#一些东西,你需要得到参数而不是哈希值。

var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        anchor = hash[1].split('#');
        vars.push(anchor[0]);
        vars[hash[0]] = anchor[0];
    }
}
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

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

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

jQuery代码片段,以获取动态变量存储在url作为参数,并将它们存储为JavaScript变量,以供您的脚本使用:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}

example.com?param1=name&param2=&id=6

$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));  
//output: Gold%20Coast

console.log(decodeURIComponent($.urlParam('city'))); 
//output: Gold Coast

如果你不知道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/