js获取url及起参数列表及扩展应用
来源:岁月联盟
时间:2012-10-20
在这里,我就列举出3类的获取参数的方法,其实质,当然,都是类似的。
第一种:1.引用外部js:<script type="text/javascript" src="js/jquery.query.js"></script>
2.设置js参数:<script type="text/javascript">
var jQuery.query={numbers:false,hash:true};
</script>
3.调用方法,获得参数:$.query.get(param1),$.query.get(param2),$.query.get(param3)......
第二种:1.引用外部js:<script type="text/javascript" src="js/jquery.query.js"></script>
2.编写脚本方法:<script type="text/javascript">
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null) return unescape(r[2]); return null;
}
</script>
3.调用方法,获得参数:GetQueryString("param1"),GetQueryString("param2"),GetQueryString("param3").....
第三种:1.引用外部js:<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
2.编写脚本方法:<script type="text/javascript">
$.extend(
getUrlVars:function(){
var vars=[],hash;
var hashes=window.location.href.slice(window.location.href.indexOf('?' )
+ 1).split( '&' );
for ( var i
= 0; i < hashes.length; i++)
{
hash = hashes[i].split( '=' );
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar:function(name){
return $.getUrlVars()[name];
}
);
</script>
3.调用方法,获得参数:$.getUrlVars();$.getUrlVar( 'name' );
由上述三种方式可以看出,我们会引用到jquery.query.js这个js文件,这个js里到底是提供了哪些方法呢,下面我们把它的代码贴出来:
Js代码
/**
* jQuery.query - Query String Modification and Creation for jQuery
* Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* Date: 2009/8/13
*
* @author Blair Mitchelmore
* @version 2.1.6
*
**/
new function(settings) {
// Various Settings
var $separator = settings.separator || '&';
var $spaces = settings.spaces === false ? false : true;
var $suffix = settings.suffix === false ? '' : '[]';
var $prefix = settings.prefix === false ? false : true;
var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
var $numbers = settings.numbers === false ? false : true;
jQuery.query = new function() {
var is = function(o, t) {
return o != undefined && o !== null && (!!t ? o.constructor == t : true);
};
var parse = function(path) {
var m, rx = //[([^[]*)/]/g, match = /^([^[]+?)(/[.*/])?$/.exec(path), base = match[1], tokens = [];
while (m = rx.exec(match[2])) tokens.push(m[1]);
return [base, tokens];
};
var set = function(target, tokens, value) {
var o, token = tokens.shift();
if (typeof target != 'object') target = null;
if (token === "") {
if (!target) target = [];
if (is(target, Array)) {
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
} else if (is(target, Object)) {
var i = 0;
while (target[i++] != null);
target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
} else {
target = [];
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
}
} else if (token && token.match(/^/s*[0-9]+/s*$/)) {
var index = parseInt(token, 10);
if (!target) target = [];
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else if (token) {
var index = token.replace(/^/s*|/s*$/g, "");
if (!target) target = {};
if (is(target, Array)) {
var temp = {};
for (var i = 0; i < target.length; ++i) {
temp[i] = target[i];
}
target = temp;
}
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else {
return value;
}
return target;
};
var queryObject = function(a) {
var self = this;
self.keys = {};
if (a.queryObject) {
jQuery.each(a.get(), function(key, val) {
self.SET(key, val);
});
} else {
jQuery.each(arguments, function() {
var q = "" + this;
q = q.replace(/^[?#]/,''); // remove any leading ? || #
q = q.replace(/[;&]$/,''); // remove any trailing & || ;
if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
jQuery.each(q.split(/[&;]/), function(){
var key = decodeURIComponent(this.split('=')[0] || "");
var val = decodeURIComponent(this.split('=')[1] || "");
if (!key) return;
if ($numbers) {
if (/^[+-]?[0-9]+/.[0-9]*$/.test(val)) // simple float regex
val = parseFloat(val);
else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
val = parseInt(val, 10);
}
val = (!val && val !== 0) ? true : val;
if (val !== false && val !== true && typeof val != 'number')
val = val;
self.SET(key, val);
});
});
}
return self;
};
queryObject.prototype = {
queryObject: true,
has: function(key, type) {
var value = this.get(key);
return is(value, type);
},
GET: function(key) {
if (!is(key)) return this.keys;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
while (target != null && tokens.length != 0) {
target = target[tokens.shift()];
}
return typeof target == 'number' ? target : target || "";
},
get: function(key) {
var target = this.GET(key);
if (is(target, Object))
return jQuery.extend(true, {}, target);
else if (is(target, Array))
return target.slice(0);
return target;
},
SET: function(key, val) {
var value = !is(val) ? null : val;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
this.keys[base] = set(target, tokens.slice(0), value);
return this;
},
set: function(key, val) {
return this.copy().SET(key, val);
},
REMOVE: function(key) {
return this.SET(key, null).COMPACT();
},
remove: function(key) {
return this.copy().REMOVE(key);
},
EMPTY: function() {
var self = this;
jQuery.each(self.keys, function(key, value) {
delete self.keys[key];
});
return self;
},
load: function(url) {
var hash = url.replace(/^.*?[#](.+?)(?:/?.+)?$/, "$1");
var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
},
empty: function() {
return this.copy().EMPTY();
},
copy: function() {
return new queryObject(this);
},
COMPACT: function() {
function build(orig) {
var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
if (typeof orig == 'object') {
function add(o, key, value) {
if (is(o, Array))
o.push(value);
else
o[key] = value;
}
jQuery.each(orig, function(key, value) {
if (!is(value)) return true;
add(obj, key, build(value));
});
}
return obj;
}
this.keys = build(this.keys);
return this;
},
compact: function() {
return this.copy().COMPACT();
},
toString: function() {
var i = 0, queryString = [], chunks = [], self = this;
var encode = function(str) {
str = str + "";
if ($spaces) str = str.replace(/ /g, "+");
return encodeURIComponent(str);
};
var addFields = function(arr, key, value) {
if (!is(value) || value === false) return;
var o = [encode(key)];
if (value !== true) {
o.push("=");
o.push(encode(value));
}
arr.push(o.join(""));
};
var build = function(obj, base) {
var newKey = function(key) {
return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
};
jQuery.each(obj, function(key, value) {
if (typeof value == 'object')
build(value, newKey(key));
else
addFields(chunks, newKey(key), value);
});
};
build(this.keys);
if (chunks.length > 0) queryString.push($hash);
queryString.push(chunks.join($separator));
return queryString.join("");
}
};
return new queryObject(location.search, location.hash);
};
}(jQuery.query || {}); // Pass in jQuery.query as settings object
由源码我们可以看出,之前调用的它的东西,在源码中都有定义,如get()方法,load()方法,toString()方法等等。它里面提供了众多的扩展方法,这个就有待大家一起去研究使用。例如:
1. 想获取test,则在引入该js后,使用如下方式获取:var value=$.query.get('key');
2. 参数列表的名称相同,则可以这样,var arrValues=$.query.get("key"); arr=[value1,value2,value3....]
3. 参数列表的名称相同,想获取第二个参数,var value2=$.query.get("key[1]")
4. 设置参数,var newKey=$.query.set("name","zhangsan").toString(); newKey : "?name=zhangsan"
5. 设置两个参数,var newKeys=$.query.set("name","zhangsan").set("age",23).toString(); newKeys : "?name=zhangsan && age=23"
6. 删除一个参数:var deleteKey=$.query.REMOVE("sex");
7. 清空所有的参数:var emptyKey=$.query.empty();
8. 复制所有参数:var copyKeys=$.query.copy();
等等以上很多,更多的源自于对源码的研究和利用,这些就靠大家自己去琢磨了,实在没有你想要的,自己再这个基础上再添加自己的想要的代码也是可以的,该js的附件我也传上点击打开链接。希望这篇文章对大家有所帮助。