是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?

如果是,怎么办?如果没有,是否有插件可以这样做?


当前回答

Roshambo jQuery方法没有处理解码URL

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

在return语句中添加时也添加了该功能

return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;

现在您可以找到更新的要点:

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}

其他回答

我接受了这个答案,并添加了对可选地将URL作为参数传入的支持;返回到window.location.search。显然,这对于从不是当前页面的URL获取查询字符串参数非常有用:

(function($, undef) {
  $.QueryString = function(url) {
    var pairs, qs = null, index, map = {};
    if(url == undef){
      qs = window.location.search.substr(1);
    }else{
      index = url.indexOf('?');
      if(index == -1) return {};
      qs = url.substring(index+1);
    }
    pairs = qs.split('&');
    if (pairs == "") return {};
    for (var i = 0; i < pairs.length; ++i)
    {
      var p = pairs[i].split('=');
      if(p.length != 2) continue;
      map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return map;
  };
})(jQuery);

这是我自己的看法。第一个函数将URL字符串解码为名称/值对的对象:

url_args_decode = function (url) {
  var args_enc, el, i, nameval, ret;
  ret = {};
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  // strip off initial ? on search and split
  args_enc = el.search.substring(1).split('&');
  for (i = 0; i < args_enc.length; i++) {
    // convert + into space, split on =, and then decode 
    args_enc[i].replace(/\+/g, ' ');
    nameval = args_enc[i].split('=', 2);
    ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
  }
  return ret;
};

另外,如果您更改了一些参数,可以使用第二个函数将参数数组放回URL字符串中:

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};

这里有一个很好的小url实用程序,带有一些很酷的糖霜:

http://www.example.com/path/index.html?silly=willy#chucky=cheese

url();            // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain');    // example.com
url('1');         // path
url('-1');        // index.html
url('?');         // silly=willy
url('?silly');    // willy
url('?poo');      // (an empty string)
url('#');         // chucky=cheese
url('#chucky');   // cheese
url('#poo');      // (an empty string)

查看更多示例并在此处下载:https://github.com/websanova/js-url#url

这些都是很好的答案,但我需要一些更强大的东西,我想你们可能都想拥有我创造的东西。

这是一种简单的库方法,可以对URL参数进行剖析和操作。静态方法有以下子方法,可以在主题URL上调用:

获取主机获取路径获取哈希setHash获取参数获取查询setParam(设置参数)获取参数hasParamremoveParam(删除参数)

例子:

URLParser(url).getParam('myparam1')

var url = "http://www.example.com/folder/mypage.html?myparam1=1&myparam2=2#something";

function URLParser(u){
    var path="",query="",hash="",params;
    if(u.indexOf("#") > 0){
        hash = u.substr(u.indexOf("#") + 1);
        u = u.substr(0 , u.indexOf("#"));
    }
    if(u.indexOf("?") > 0){
        path = u.substr(0 , u.indexOf("?"));
        query = u.substr(u.indexOf("?") + 1);
        params= query.split('&');
    }else
        path = u;
    return {
        getHost: function(){
            var hostexp = /\/\/([\w.-]*)/;
            var match = hostexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getPath: function(){
            var pathexp = /\/\/[\w.-]*(?:\/([^?]*))/;
            var match = pathexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getHash: function(){
            return hash;
        },
        getParams: function(){
            return params
        },
        getQuery: function(){
            return query;
        },
        setHash: function(value){
            if(query.length > 0)
                query = "?" + query;
            if(value.length > 0)
                query = query + "#" + value;
            return path + query;
        },
        setParam: function(name, value){
            if(!params){
                params= new Array();
            }
            params.push(name + '=' + value);
            for (var i = 0; i < params.length; i++) {
                if(query.length > 0)
                    query += "&";
                query += params[i];
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
        getParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return decodeURIComponent(pair[1]);
                }
            }
            console.log('Query variable %s not found', name);
        },
        hasParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return true;
                }
            }
            console.log('Query variable %s not found', name);
        },
        removeParam: function(name){
            query = "";
            if(params){
                var newparams = new Array();
                for (var i = 0;i < params.length;i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) != name)
                          newparams .push(params[i]);
                }
                params = newparams;
                for (var i = 0; i < params.length; i++) {
                    if(query.length > 0)
                        query += "&";
                    query += params[i];
                }
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
    }
}

document.write("Host: " + URLParser(url).getHost() + '<br>');
document.write("Path: " + URLParser(url).getPath() + '<br>');
document.write("Query: " + URLParser(url).getQuery() + '<br>');
document.write("Hash: " + URLParser(url).getHash() + '<br>');
document.write("Params Array: " + URLParser(url).getParams() + '<br>');
document.write("Param: " + URLParser(url).getParam('myparam1') + '<br>');
document.write("Has Param: " + URLParser(url).hasParam('myparam1') + '<br>');

document.write(url + '<br>');

// Remove the first parameter
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove the first parameter<br>');

// Add a third parameter
url = URLParser(url).setParam('myparam3',3);
document.write(url + ' - Add a third parameter<br>');

// Remove the second parameter
url = URLParser(url).removeParam('myparam2');
document.write(url + ' - Remove the second parameter<br>');

// Add a hash
url = URLParser(url).setHash('newhash');
document.write(url + ' - Set Hash<br>');

// Remove the last parameter
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove the last parameter<br>');

// Remove a parameter that doesn't exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a parameter that doesn\"t exist<br>');

我认为这是实现这一点的准确和简洁的方法(修改自http://css-tricks.com/snippets/javascript/get-url-variables/):

function getQueryVariable(variable) {

    var query = window.location.search.substring(1),            // Remove the ? from the query string.
        vars = query.split("&");                                // Split all values by ampersand.

    for (var i = 0; i < vars.length; i++) {                     // Loop through them...
        var pair = vars[i].split("=");                          // Split the name from the value.
        if (pair[0] == variable) {                              // Once the requested value is found...
            return ( pair[1] == undefined ) ? null : pair[1];   // Return null if there is no value (no equals sign), otherwise return the value.
        }
    }

    return undefined;                                           // Wasn't found.

}