[JS]window.location獲取url各項參數詳解


window.location方法后還還可以帶href,search等參數,下面我們來看看獲取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.php230.com :80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

我們可以用javascript獲得其中的各個部分
1, window.location.href
整個URl字符串(在瀏覽器中就是完整的地址欄)
本例返回值:
代碼如下 復制代碼
http://www.php230.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.php230.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

 

項目中的應用:

//獲取頁面根目錄的下一級目錄
//頁面地址:http://192.168.2.98:8020/house-wap/src/main/webapp/user/userCenter.html
//所獲取的地址:http://192.168.1.105:6082/house-wap/
function getRootPath(){ 
    var pathName = window.location.pathname.substring(1);     
    console.log(pathName);    
     if(pathName == '') {
             webname=''
         }else{
             webName=pathName.substring(0, pathName.indexOf('/'))
     };    
    console.log(webName);    
    return window.location.protocol + '//' + window.location.host + '/'+ webName + '/'; 
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM