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

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


当前回答

可靠地做这件事比一开始想象的要复杂得多。

其他答案中使用的location.search很脆弱,应该避免使用-例如,如果有人搞砸了,并在?查询字符串。在我看来,URL在浏览器中自动转义的方式有很多种,这使得decodeURIComponent非常强制性。许多查询字符串是由用户输入生成的,这意味着对URL内容的假设非常糟糕。包括非常基本的东西,比如每个键都是唯一的,甚至有一个值。

为了解决这个问题,这里提供了一个可配置的API,并提供了健康的防御性编程。请注意,如果您愿意对某些变量进行硬编码,或者如果输入不能包含hasOwnProperty等,则可以将其大小减半。

版本1:返回包含每个参数的名称和值的数据对象。它有效地消除了重复,并始终尊重从左到右找到的第一个。

function getQueryData(url, paramKey, pairKey, missingValue, decode) {

    var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;

    if (!url || typeof url !== 'string') {
        url = location.href; // more robust than location.search, which is flaky
    }
    if (!paramKey || typeof paramKey !== 'string') {
        paramKey = '&';
    }
    if (!pairKey || typeof pairKey !== 'string') {
        pairKey = '=';
    }
    // when you do not explicitly tell the API...
    if (arguments.length < 5) {
        // it will unescape parameter keys and values by default...
        decode = true;
    }

    queryStart = url.indexOf('?');
    if (queryStart >= 0) {
        // grab everything after the very first ? question mark...
        query = url.substring(queryStart + 1);
    } else {
        // assume the input is already parameter data...
        query = url;
    }
    // remove fragment identifiers...
    fragStart = query.indexOf('#');
    if (fragStart >= 0) {
        // remove everything after the first # hash mark...
        query = query.substring(0, fragStart);
    }
    // make sure at this point we have enough material to do something useful...
    if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
        // we no longer need the whole query, so get the parameters...
        query = query.split(paramKey);
        result = {};
        // loop through the parameters...
        for (i = 0, len = query.length; i < len; i = i + 1) {
            pairKeyStart = query[i].indexOf(pairKey);
            if (pairKeyStart >= 0) {
                name = query[i].substring(0, pairKeyStart);
            } else {
                name = query[i];
            }
            // only continue for non-empty names that we have not seen before...
            if (name && !Object.prototype.hasOwnProperty.call(result, name)) {
                if (decode) {
                    // unescape characters with special meaning like ? and #
                    name = decodeURIComponent(name);
                }
                if (pairKeyStart >= 0) {
                    value = query[i].substring(pairKeyStart + 1);
                    if (value) {
                        if (decode) {
                            value = decodeURIComponent(value);
                        }
                    } else {
                        value = missingValue;
                    }
                } else {
                    value = missingValue;
                }
                result[name] = value;
            }
        }
        return result;
    }
}

版本2:返回一个具有两个相同长度数组的数据映射对象,一个用于名称,另一个用于值,每个参数都有一个索引。此格式支持重复名称,并故意不消除重复名称,因为这可能就是您希望使用此格式的原因。

function getQueryData(url, paramKey, pairKey, missingValue, decode) {

    var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;

    if (!url || typeof url !== 'string') {
          url = location.href; // more robust than location.search, which is flaky
    }
        if (!paramKey || typeof paramKey !== 'string') {
            paramKey = '&';
        }
        if (!pairKey || typeof pairKey !== 'string') {
            pairKey = '=';
        }
        // when you do not explicitly tell the API...
        if (arguments.length < 5) {
            // it will unescape parameter keys and values by default...
            decode = true;
        }

        queryStart = url.indexOf('?');
        if (queryStart >= 0) {
            // grab everything after the very first ? question mark...
            query = url.substring(queryStart + 1);
        } else {
            // assume the input is already parameter data...
            query = url;
        }
        // remove fragment identifiers...
        fragStart = query.indexOf('#');
        if (fragStart >= 0) {
            // remove everything after the first # hash mark...
            query = query.substring(0, fragStart);
        }
        // make sure at this point we have enough material to do something useful...
        if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
            // we no longer need the whole query, so get the parameters...
            query = query.split(paramKey);
            result = {
                names: [],
                values: []
            };
            // loop through the parameters...
            for (i = 0, len = query.length; i < len; i = i + 1) {
                pairKeyStart = query[i].indexOf(pairKey);
                if (pairKeyStart >= 0) {
                    name = query[i].substring(0, pairKeyStart);
                } else {
                    name = query[i];
                }
                // only continue for non-empty names...
                if (name) {
                    if (decode) {
                        // unescape characters with special meaning like ? and #
                        name = decodeURIComponent(name);
                    }
                    if (pairKeyStart >= 0) {
                        value = query[i].substring(pairKeyStart + 1);
                        if (value) {
                            if (decode) {
                                value = decodeURIComponent(value);
                            }
                        } else {
                            value = missingValue;
                        }
                    } else {
                        value = missingValue;
                    }
                    result.names.push(name);
                    result.values.push(value);
                }
           }
           return result;
       }
   }

其他回答

如果您使用的是jQuery,那么可以使用一个库,例如jQueryBBQ:返回按钮和查询库。

…jQueryBBQ提供了一个完整的.depam()方法,以及哈希状态管理、片段/查询字符串解析和合并实用程序方法。

编辑:添加参数示例:

var DeparamExample=函数(){var params=$.depam.querystring();//nameofram是来自url的参数的名称//如果ajax使用哈希刷新,下面的代码将获取参数if(typeof params.nameofram==“undefined”){params=jQuery.departam.frage(window.location.href);}if(typeof params.nameofram!=“undefined”){var paramValue=params.nameofram.toString();}};

如果您只想使用纯JavaScript,可以使用。。。

var getParamValue = (function() {
    var params;
    var resetParams = function() {
            var query = window.location.search;
            var regex = /[?&;](.+?)=([^&;]+)/g;
            var match;

            params = {};

            if (query) {
                while (match = regex.exec(query)) {
                    params[match[1]] = decodeURIComponent(match[2]);
                }
            }    
        };

    window.addEventListener
    && window.addEventListener('popstate', resetParams);

    resetParams();

    return function(param) {
        return params.hasOwnProperty(param) ? params[param] : null;
    }

})();​

由于新的HTML历史API,特别是History.pushState()和History.replaceState(),URL可能会发生更改,这将使参数及其值的缓存无效。

此版本将在每次更改历史记录时更新其内部参数缓存。

我使用以下代码(JavaScript)获取通过URL传递的内容:

function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;
        }

然后,要将值分配给变量,只需指定要获取的参数,例如,如果URL是example.com/?I=1&p=2&f=3

您可以执行此操作以获取值:

var getI = getUrlVars()["I"];
var getP = getUrlVars()["p"];
var getF = getUrlVars()["f"];

则值将为:

getI = 1, getP = 2 and getF = 3

非常轻量级的jQuery方法:

var qs = window.location.search.replace('?','').split('&'),
    request = {};
$.each(qs, function(i,v) {
    var initial, pair = v.split('=');
    if(initial = request[pair[0]]){
        if(!$.isArray(initial)) {
            request[pair[0]] = [initial]
        }
        request[pair[0]].push(pair[1]);
    } else {
        request[pair[0]] = pair[1];
    }
    return;
});
console.log(request);

例如,提醒?q

alert(request.q)

获取所有querystring参数,包括复选框值(数组)。

考虑到GET参数的正确和正常使用,我认为在大多数函数中,它缺少的是对数组的支持和删除哈希数据。

所以我写了这个函数:

function qs(a){
 if(!a)return {};
 a=a.split('#')[0].split('&');
 var b=a.length,c={},d,k,v;
 while(b--){
  d=a[b].split('=');
  k=d[0].replace('[]',''),v=decodeURIComponent(d[1]||'');
  c[k]?typeof c[k]==='string'?(c[k]=[v,c[k]]):(c[k].unshift(v)):c[k]=v;
 }
 return c
}

使用速记运算符&while--loop,性能应该非常好。

支持:

空值(key=/key)键值(Key=value)数组(键[]=值)哈希(哈希标签被拆分)

笔记:

它不支持对象数组(key[key]=value)

如果空格为+,则保留为+。

如果需要,添加替换(/\+/g,“”)。

用法:

qs('array[]=1&array[]=2&key=value&empty=&empty2#hash')

返回:

{
    "empty": "",
    "key": "value",
    "array": [
        "1",
        "2"
    ]
}

演示:

http://jsfiddle.net/ZQMrt/1/

Info

如果你不明白什么,或者你读不懂函数,就问问。我很高兴解释我在这里做了什么。

如果您认为该函数不可读且无法维护,我很乐意为您重写该函数,但请考虑速记和按位运算符总是比标准语法更快(可能在ECMA-262书中阅读有关速记和按位数运算符的信息,或使用您最爱的搜索引擎)。用标准可读语法重写代码意味着性能损失。

我宁愿使用split()而不是Regex执行此操作:

function getUrlParams() {
    var result = {};
    var params = (window.location.search.split('?')[1] || '').split('&');
    for(var param in params) {
        if (params.hasOwnProperty(param)) {
            var paramParts = params[param].split('=');
            result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
        }
    }
    return result;
}