Javascript Url處理

來源:互聯網
上載者:User
JavaScript擷取URL

 

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直接定位到某一名詞解釋。(也稱為錨點)

下面我們舉例一個URL,然後獲得它的各個組成部分。

http://www.nowamagic.net/newsDetail.php?id=65
window.location.href

可以獲得整個URL字串(在瀏覽器中就是完整的地址欄)。

1 var test = window.location.href;
2 alert(test);

程式返回 http://www.nowamagic.net/newsDetail.php?id=65

window.location.protocol

可以獲得 URL 的協議部分

1 var test = window.location.protocol;
2 alert(test);

程式返回 http:

window.location.host

可以獲得 URL 的主機部分

1 var test = window.location.host;
2 alert(test);

程式返回 www.nowamagic.net

window.location.port

可以獲得 URL 的連接埠部分

1 var test = window.location.port;
2 alert(test);

如果採用預設的80連接埠(update:即使添加了:80),那麼傳回值並不是預設的80而是Null 字元。

window.location.pathname

獲得 URL 的路徑部分(就是檔案地址)

1 var test = window.location.pathname;
2 alert(test);
window.location.search

獲得查詢(參數)部分,除了給動態語言賦值以外,我們同樣可以給靜態頁面,並使用javascript來獲得相信應的參數值。

 
1 var test = window.location.search;
2 alert(test);
window.location.hash

獲得錨點。

1 var test = window.location.hash;
2 alert(test);
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.