例如:url为xxxx/test.html?username=1&num=2&id=1
1.1 首先了解一下window.location属性
window.location 对象所包含的属性
属性 | 描述 |
---|---|
hash | 从井号 (#) 开始的 URL(锚) |
host | 主机名和当前 URL 的端口号 |
hostname | 当前 URL 的主机名 |
href | 完整的 URL |
pathname | 当前 URL 的路径部分 |
port | 当前 URL 的端口号 |
protocol | 当前 URL 的协议 |
search | 从问号 (?) 开始的 URL(查询部分) |
在这里,有window.location.search,即为从?开始的带有参数的url部分,想得到这部分的每个参数,就要考虑进行字符串截取。在这之后有很多方法,这里列举出两种方法。
1.2 使用正则来匹配参数
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r != null){
return decodeuricomponent(r[2]);
}else{
return null;
}
}
- 使用正则匹配以空或者&作为开始,最后以&或空作为结束的字符串。
- 将得到的”?username=1&num=2&id=1”的问号去掉。
- 经过正则匹配后,返回的值为:
其中,第一个元素为匹配出来的具体内容,元素1,2,3分别为三个模式单元,这里要拿到num的值,所以返回r[2],由于浏览器默认会对中文和一些特殊字符进行编码,最后对内容作了一个解码。
1.3 使用split函数
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
}
}
return theRequest;
}
//然后我们通过调用此函数获取对应参数值:
var Request = new Object();
Request = GetRequest();
/*
var 参数1,参数2,参数3,参数N;
参数1 = Request[''参数1''];
参数2 = Request[''参数2''];
参数3 = Request[''参数3''];
参数N = Request[''参数N''];
*/