
在 JavaScript 中存取 GET 參數
可以使用 window.location 物件在 HTML 頁面的 JavaScript 中擷取 GET 參數。若要取得不帶問號的GET 參數,請使用以下程式碼:
1 | window.location.search. substr (1)
|
登入後複製
例如,給定URL:
上面的程式碼將輸出:
函數的替代方法
建立函數擷取特定GET 參數,請使用:
1 2 3 4 5 6 7 8 9 10 11 12 | function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
. substr (1)
.split( "&" )
.forEach( function (item) {
tmp = item.split( "=" );
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
|
登入後複製
使用findGetParameter('returnurl') 調用函數將返回“/admin。”
Plain For Loop Variation
為了與IE8 等舊版瀏覽器相容,請使用普通的for循環:
1 2 3 4 5 6 7 8 9 10 | function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search. substr (1).split( "&" );
for ( var index = 0; index < items.length; index++) {
tmp = items[index].split( "=" );
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
|
登入後複製
以上是如何在 JavaScript 中存取和檢索 GET 參數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!