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); var arr = str.split(“ & ”); 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
|
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);
alert(window.location.href);
alert(window.location.port);
alert(window.location.protocol);
alert(window.location.hash);
alert(window.location.host);
alert(window.location.search);
|