一. 擷取url的querystring參數
擷取url的querystring參數的兩種方法如下:
1.1 方法一:正則匹配
//擷取url中的參數
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", i); // 匹配目標參數
var result = window.location.search.substr(1).match(reg); // 對querystring匹配目標參數
if (result != null) {
return decodeURIComponent(result[2]);
} else {
return null;
}
}
對於 http://localhost/index.html?q1=abc&q2=efg&q3=h 的url,擷取 q1 參數值的方法如下:
var q1 = getQueryString('q1'); // abc
1.2 方法二:split
function getQueryString() {
var qs = location.search.substr(1), // 擷取url中"?"符後的字串
args = {}, // 儲存參數資料的對象
items = qs.length ? qs.split("&") : [], // 取得每一個參數項,
item = null,
len = items.length;
for(var i = 0; i < len; i++) {
item = items[i].split("=");
var name = decodeURIComponent(item[0]),
value = decodeURIComponent(item[1]);
if(name) {
args[name] = value;
}
}
return args;
}
對於 http://localhost/index.html?q1=abc&q2=efg&q3=h 的url,擷取 q1 參數值的方法如下:
var qs = getQueryString();
var q1 = qs["q1"]; // abc
用上面的getQueryString()方法能很好的解決擷取url的querystring參數問題。就
上面兩種getQueryString()方法都能很好地解決擷取url的querystring參數問題。就此順便整理一下Location對象,方便日後學習參考。
二. Location對象的屬性
備忘:以 http://localhost:80/dir/index.html?q1=abc&q2=efg&q3=h#anchor 為例:
屬性 定義 樣本
hash 返回URL中的hash(#後跟零或多個字串) #anchor
host 相當於hostname + port,即:主機名稱(網域名稱)+連接埠號碼 localhost:80
hostname 主機名稱(網域名稱) localhost
href 當前頁面的完整URL http://localhost:80/dir/index.html?q1=abc&q2=efg&q3=h#anchor
pathname URL中的目錄和檔案名稱/dir/index.html
port 連接埠號碼 80
protocal 協議 http:
search 查詢字串。這個字元以問號開頭 ?q1=abc&q2=efg&q3=h
location的這8個屬性都是可讀寫的。
其中,改變location.href會跳轉到新的URL頁面,而修改location.hash會跳到當前頁面中錨點位置。
每次修改window.location的屬性(hash除外),頁面都會以新的URL重新載入,並在瀏覽器的曆史紀錄中產生一條新紀錄。
三. Location對象的方法
方法 說明
assign(url) 開啟新的URL,並在瀏覽器的曆史紀錄中產生一條記錄。
replace(url) 開啟新的URL,但是不會在瀏覽器的曆史紀錄中產生新紀錄。
reload(force) 重新整理當前頁面。force為true時從伺服器端重新載入;為false時從瀏覽器緩衝中重新載入。預設值false。
其中,location.assign(url) 的效果跟下列兩行代碼的效果完全一樣:
window.location = url;
location.href = url;
位於 location.reload() 調用之後的代碼可能會也可能不會執行,這取決於網路延遲或系統資源等因素。因此,最好將 location.reload() 放在代碼的最後一行。