当前位置:编程学习 > JS >>

javascript window.location获取url各项参数详解

URL即:统一资源定位符 (Uniform Resource Locator, URL)
完整的URL由这几个部分构成:
scheme://host:port/path?query#fragment
scheme:通信协议
常用的http,ftp,maito等


http://localhost/test/test.htm?id=1

 代码如下 复制代码

<html>
<head>
</head>
<body>
<script languge=javascript>
alert(window.location.pathname);   --返回   /test/test.htm
alert(window.location.search);        --返回   ?id=1
alert(window.location.href);             --返回   http://localhost/test/test.htm?id=1
</script>
</body>
</html>

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参数)之后的字符串. 

 


对于这样一个URL

 代码如下 复制代码

http://www.hzhuti.com :80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

我们可以用javascript获得其中的各个部分
1, window.location.href
整个URl字符串(在浏览器中就是完整的地址栏)
本例返回值:

 代码如下 复制代码
http://www.hzhuti.com :80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

2,window.location.protocol
URL 的协议部分
本例返回值:http:

3,window.location.host
URL 的主机部分
本例返回值:www.hzhuti.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

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,