是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
下面是我将Andy E的优秀解决方案打造成一个成熟的jQuery插件的尝试:
;(function ($) {
$.extend({
getQueryString: function (name) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[name];
}
});
})(jQuery);
语法为:
var someVar = $.getQueryString('myParam');
两全其美!
其他回答
这是我在GitHub上的查询字符串解析代码版本。
它的前缀是jquery.*,但解析函数本身不使用jquery。它非常快,但仍然可以进行一些简单的性能优化。
它还支持URL中的列表和哈希表编码,例如:
arr[]=10&arr[]=20&arr[]=100
or
hash[key1]=hello&hash[key2]=moto&a=How%20are%20you
jQuery.toQueryParams = function(str, separator) {
separator = separator || '&'
var obj = {}
if (str.length == 0)
return obj
var c = str.substr(0,1)
var s = c=='?' || c=='#' ? str.substr(1) : str;
var a = s.split(separator)
for (var i=0; i<a.length; i++) {
var p = a[i].indexOf('=')
if (p < 0) {
obj[a[i]] = ''
continue
}
var k = decodeURIComponent(a[i].substr(0,p)),
v = decodeURIComponent(a[i].substr(p+1))
var bps = k.indexOf('[')
if (bps < 0) {
obj[k] = v
continue;
}
var bpe = k.substr(bps+1).indexOf(']')
if (bpe < 0) {
obj[k] = v
continue;
}
var bpv = k.substr(bps+1, bps+bpe-1)
var k = k.substr(0,bps)
if (bpv.length <= 0) {
if (typeof(obj[k]) != 'object') obj[k] = []
obj[k].push(v)
} else {
if (typeof(obj[k]) != 'object') obj[k] = {}
obj[k][bpv] = v
}
}
return obj;
}
从MDN:
function loadPageVar (sVar) {
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
alert(loadPageVar("name"));
我使用以下代码(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
这些都是很好的答案,但我需要一些更强大的东西,我想你们可能都想拥有我创造的东西。
这是一种简单的库方法,可以对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>');
snipplr.com上的Roshambo有一个简单的脚本来实现这一点,这在使用jQuery|Improved获取URL参数中有所描述。使用他的脚本,您还可以轻松地提取所需的参数。
要点如下:
$.urlParam = function(name, url) {
if (!url) {
url = window.location.href;
}
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
if (!results) {
return undefined;
}
return results[1] || undefined;
}
然后从查询字符串中获取参数。
那么,如果URL/查询字符串是xyz.example/index.html?lang=de。
只需调用var langval=$.urlParam('lang');,你已经得到了。
UZBEKJON也在这方面发表了一篇很棒的博客文章,用jQuery获取URL参数和值。