0%

用JS获取URL中的参数

js获取URL中的一些参数的意思
location对象 含有当前URL的信息. 属性 href 整个URL字符串.
protocol 含有URL第一部分的字符串,如http:
host 包含有URL中主机名:端口号部分的字符串.如//www.cenpok.net/server/
hostname 包含URL中主机名的字符串.如http://www.cenpok.net ;
port 包含URL中可能存在的端口号字符串.
pathname URL中”/”以后的部分.如~list/index.htm
hash “#”号(CGI参数)之后的字符串.
search “?”号(CGI参数)之后的字符串.

第一种:只适用于/User/vip_card_manager?useless=219

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function UrlSearch() {
var name, value;
var str = location.href; //取得整个地址栏
var num = str.indexOf(“ ? ”)
str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ]
var arr = str.split(“ & ”); //各个参数放到数组里 console.log(arr)
for (var i = 0; i < arr.length; i++) {
num = arr[i].indexOf(“ = ”);
if (num > 0) {
name = arr[i].substring(0, num);
value = arr[i].substr(num + 1);
this[name] = value;
}
}
}

第二种:
适应以下两种模式,来获取url参数值:
/User/vip_card_manager/useless/219/id/18
/User/vip_card_manager?useless=219&id=18

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
console.log(getQueryString(“useless”));

function getQueryString(name) {
var reg = new RegExp(“( ^ | & )” + name + “ = ([ ^ & ] * )( & | $)”, “i”);
var reg_rewrite = new RegExp("( ^ | /)” + name + “/([ ^ /]*)(/ | $)”, “i”);")
var r = window.location.search.substr(1).match(reg);
var q = window.location.pathname.substr(1).match(reg_rewrite);
if (r != null) {
return unescape(r[2]);
} else if (q != null) {
return unescape(q[2]);
} else {
return null;
}
}

第三种:自己没有用过,是同事给的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 获取指定的URL参数值
* URL:http://www.quwan.com/index?name=tyler
* 参数:paramName URL参数
* 调用方法:getParam(“name”)
* 返回值:tyler
*/function getParam(paramName) {
paramValue = “”, isFound = !1;
if (this.location.search.indexOf(“?”) == 0 && this.location.search.indexOf(“=”) > 1) {
arrSource = unescape(this.location.search).substring(1, this.location.search.length).split(“&”), i = 0;
while (i < arrSource.length && !isFound) arrSource[i].indexOf(“=”) > 0 && arrSource[i].split(“=”)[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split(“=”)[1], isFound = !0), i++
}
return paramValue == “” && (paramValue = null), paramValue
}
//设置或获取对象指定的文件名或路径。
alert(window.location.pathname);
//设置或获取整个 URL 为字符串。
alert(window.location.href);
//设置或获取与 URL 关联的端口号码。
alert(window.location.port);
//设置或获取 URL 的协议部分。
alert(window.location.protocol);
//设置或获取 href 属性中在井号“#”后面的分段。
alert(window.location.hash);
//设置或获取 location 或 URL 的 hostname 和 port 号码。
alert(window.location.host);
//设置或获取 href 属性中跟在问号后面的部分。
alert(window.location.search);