本篇文章,我将介绍一下如何利用 js获取url当中“?”后面的参数。下面将介绍几种方法。
1、方法介绍
//方法一:正则分析法
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}
var videoId = getQueryString("videoId");
//方法二
<Script language="javascript">
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]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
</script>
//使用方法:
<Script language="javascript">
var Request = new Object();
Request = GetRequest();
var 参数1,参数2,参数3,参数N;
参数1 = Request[''参数1''];
参数2 = Request[''参数2''];
参数3 = Request[''参数3''];
参数N = Request[''参数N''];
</Script>
//方法三:
/**
* 获取指定的URL参数值
* URL:http://www.quwan.com/index?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
}
2、其他参数获取介绍:
//设置或获取对象指定的文件名或路径。
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);
URL即:统一资源定位符 (Uniform Resource Locator, URL)
完整的URL由这几个部分构成:
scheme://host:port/path?query#fragment
scheme:通信协议
常用的http,ftp,maito等
host:主机
服务器(计算机)域名系统 (DNS) 主机名或 IP 地址。
port:端口号
整数,可选,省略时使用方案的默认端口,如http的默认端口为80。
path:路径
由零或多个”/”符号隔开的字符串,一般用来表示主机上的一个目录或文件地址。
query:查询
可选,用于给动态网页(如使用CGI、ISAPI、PHP/JSP/ASP/ASP.NET等技术制作的网页)传递参数,可有多个参数,用”&”符号隔开,每个参数的名和值用”=”符号隔开。
fragment:信息片断
字符串,用于指定网络资源中的片断。例如一个网页中有多个名词解释,可使用fragment直接定位到某一名词解释。(也称为锚点.)
3、实例展示
对于这样一个URL:
http://www.maidq.com/index.html?ver=1.0&id=6#imhere
我们可以用javascript获得其中的各个部分
1, window.location.href
整个URl字符串(在浏览器中就是完整的地址栏)
本例返回值: http://www.maidq.com/index.html?ver=1.0&id=6#imhere
2,window.location.protocol
URL 的协议部分
本例返回值:http:
3,window.location.host
URL 的主机部分
本例返回值:www.maidq.com
4,window.location.port
URL 的端口部分
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:”“
5,window.location.pathname
URL 的路径部分(就是文件地址)
本例返回值:/fisker/post/0703/window.location.html
6,window.location.search
查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?ver=1.0&id=6
7,window.location.hash
锚点
本例返回值:#imhere