是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
我接受了这个答案,并添加了对可选地将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);
其他回答
此函数将根据需要使用递归返回已解析的JavaScript对象,其中包含任意嵌套的值。
这里有一个jsfiddle示例。
[
'?a=a',
'&b=a',
'&b=b',
'&c[]=a',
'&c[]=b',
'&d[a]=a',
'&d[a]=x',
'&e[a][]=a',
'&e[a][]=b',
'&f[a][b]=a',
'&f[a][b]=x',
'&g[a][b][]=a',
'&g[a][b][]=b',
'&h=%2B+%25',
'&i[aa=b',
'&i[]=b',
'&j=',
'&k',
'&=l',
'&abc=foo',
'&def=%5Basf%5D',
'&ghi=[j%3Dkl]',
'&xy%3Dz=5',
'&foo=b%3Dar',
'&xy%5Bz=5'
].join('');
给出以上任何测试示例。
var qs = function(a) {
var b, c, e;
b = {};
c = function(d) {
return d && decodeURIComponent(d.replace(/\+/g, " "));
};
e = function(f, g, h) {
var i, j, k, l;
h = h ? h : null;
i = /(.+?)\[(.+?)?\](.+)?/g.exec(g);
if (i) {
[j, k, l] = [i[1], i[2], i[3]]
if (k === void 0) {
if (f[j] === void 0) {
f[j] = [];
}
f[j].push(h);
} else {
if (typeof f[j] !== "object") {
f[j] = {};
}
if (l) {
e(f[j], k + l, h);
} else {
e(f[j], k, h);
}
}
} else {
if (f.hasOwnProperty(g)) {
if (Array.isArray(f[g])) {
f[g].push(h);
} else {
f[g] = [].concat.apply([f[g]], [h]);
}
} else {
f[g] = h;
}
return f[g];
}
};
a.replace(/^(\?|#)/, "").replace(/([^#&=?]+)?=?([^&=]+)?/g, function(m, n, o) {
n && e(b, c(n), c(o));
});
return b;
};
如果需要数组样式参数,URL.js支持任意嵌套的数组样式参数以及字符串索引(映射)。它还处理URL解码。
url.get("val[0]=zero&val[1]=one&val[2]&val[3]=&val[4]=four&val[5][0]=n1&val[5][1]=n2&val[5][2]=n3&key=val", {array:true});
// Result
{
val: [
'zero',
'one',
true,
'',
'four',
[ 'n1', 'n2', 'n3' ]
]
key: 'val'
}
试试看:
String.prototype.getValueByKey = function(k){
var p = new RegExp('\\b'+k+'\\b','gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};
然后这样称呼:
if(location.search != "") location.search.getValueByKey("id");
您还可以将此用于cookie:
if(navigator.cookieEnabled) document.cookie.getValueByKey("username");
这只适用于key=value[&|;|$]。。。将无法处理对象/数组。
如果您不想使用String.prototype。。。将其移动到函数并将字符串作为参数传递
快速、轻松、快速:
功能:
function getUrlVar() {
var result = {};
var location = window.location.href.split('#');
var parts = location[0].replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
result [key] = value;
});
return result;
}
用法:
var varRequest = getUrlVar()["theUrlVarName"];
这些都是很好的答案,但我需要一些更强大的东西,我想你们可能都想拥有我创造的东西。
这是一种简单的库方法,可以对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>');