本文實(shí)例講述了JS基于Location實(shí)現(xiàn)訪問Url、重定向及刷新頁面的方法。分享給大家供大家參考,具體如下:
js通過Location實(shí)現(xiàn)訪問Url,重定向,刷新頁
web中經(jīng)常會使用到刷新頁面,訪問url、重定向請求的功能。
javascript提供了許多方法訪問,修改當(dāng)前用戶在瀏覽器中訪問的url.所有的這些技術(shù)都是基于location對象的。它是作為window對象的屬性。你可以生成一個(gè)包含當(dāng)前url的新location對象:
var currentURL=window.location;
在這片文章你將看到location對象的所有屬性和方法,你將學(xué)到:
怎么讀取url不同部分 怎么重定向網(wǎng)頁 怎么自動刷新或重載頁面.URL有6部分組成,一些是可選的:
<協(xié)議>//<域名>:<端口>/<路徑><查詢參數(shù)><hash>
<protocol>//<hostname>:<port>/<pathname><search><hash>
協(xié)議和域名是必須項(xiàng),其它是可選項(xiàng)。
下面是一個(gè)包含所有部分的URL例子:
http://www.example.com:80/example.cgi?x=3&y=4#results
在這個(gè)例子中, http: 是 協(xié)議, www.example.com 是 域名, 80 是端口, /example.cgi 是路徑, ?x=3&y=4是查詢字符串, #results是hash, 或頁面內(nèi)部的錨點(diǎn).
你可以使用location對象的protocol,hostname,port,pathname,search,hash屬性訪問URL各個(gè)部分。你還可以使用下面屬性:
host
包含域名和端口例如: www.example.com:80
href
包含整個(gè)URL例如:http://www.example.com:80/example.cgi?x=3&y=4#results
示例:
var currentURL=window.location;alert(currentURL.href);//Displays'http://www.example.com:80/example.cgi?x=3&y=4#results'alert(currentURL.protocol);//Displays'http:'alert(currentURL.host);//Displays'www.example.com:80'alert(currentURL.hostname);//Displays'www.example.com'alert(currentURL.port);//Displays'80'alert(currentURL.pathname);//Displays'/example.cgi'alert(currentURL.search);//Displays'?x=3&y=4'alert(currentURL.hash);//Displays'#results'
你可以使用location的href屬性,把頁面跳轉(zhuǎn)到不同于當(dāng)前頁面的頁面。
window.location. rel="external nofollow" ;
示例:
<input type="button" onclick="window.location.Visit www.google.com"/>
使用Location的href屬性跳轉(zhuǎn)頁面,前一頁的Url會保存在瀏覽器的history歷史中。當(dāng)用戶點(diǎn)擊瀏覽器的“后退”按鈕可以返回前一頁。如果你不想讓返回前一頁可使用Location.replace()代替:
window.location.replace("http://www.example.com/anotherpage.html");
新聞熱點(diǎn)
疑難解答
圖片精選