2012年11月14日 星期三

[宅] javascript筆記 - window.location類別

window.location是個非常好用的物件,除了可以跳轉外,他還提供了很多讀取所在網址的相關資訊。我們先來看看"http://cat-son.blogspot.tw?foo=bar#a"這個頁面的window.location的attributes:

assign: function () { [native code] } //跳轉
hash: "#a" //取得錨點
host: "cat-son.blogspot.tw"
hostname: "cat-son.blogspot.tw"
href: "http://cat-son.blogspot.tw/#a"
origin: "http://cat-son.blogspot.tw"
pathname: "/"
port: ""
protocol: "http:"
reload: function () { [native code] }
replace: function () { [native code] }
search: "?foo=bar" //網址後的query值>

頁面跳轉

可以用以下幾種方法直接修改window.location的值:
window.location="http://example.com";
window.location.href="http://example.com";
location="http://example.com";
location.href="http://example.com";
或是使用window.location所提供的function來跳轉:
window.location.assign("http://example.com");
window.location.replace("http://example.com");
assign()和replace()效果差不多,差別在於replace是置換掉現在的document,不會留下被置換掉的頁面紀錄,所以當你按下"上一頁"時回到的其實是你"上上個"看到的頁面....
這樣講一定聽不懂,舉個例來說好了:

當我從A頁面逛到B頁面後,在B頁面執行了location.replace(C頁面),會把當前的document從B換成C,所以當我點上一頁時就是回到A。示意:
A-->B
↓
location.replace(C)
↓
A-->C
而使用location.assign則會是這樣的情況:
A-->B
↓
location.assign(C)
↓
A-->B-->C
所以在C頁面點上一頁會回到B而不是A


取得資訊

很多時候我們使用get這種方式來傳遞資料時,傳遞的資料會出現在網址後端,這時我們就可以從window.location.search這個字串拿到query值。例如在"http://example.com/?foo=bar"的頁面下,我們的window.location.search就會是"?foo=bar"
window.location.hash則是achor的值,也就是錨點。
但要注意的是,網址中只要在"#"之後的字串都會被視為hash,所以當你要同時傳遞anchor和query時,務必要把anchor放在最後面,例如:
"http://cat-son.blogspot.tw?foo=bar#a"


重讀頁面

使用window.location.reload(forceGet)
forceGet是個布林值,預設為false,代表只要從cache中重新載入就好,不需要再向server做http request;反之為true時,代表一定要再向server重新要資料。
這個特性還滿重要的,可以避免重讀時拿到舊資料,同樣的目的可以透過加上隨機的query值來達成。


小補充

關於document.location和window.location的差別:
window.location is read/write on all compliant browsers.
document.location is read-only in Internet Explorer (at least), but read/write in Gecko-based browsers (Firefox, SeaMonkey).