首頁 > web前端 > js教程 > 如何在 JavaScript 中存取和檢索 GET 參數?

如何在 JavaScript 中存取和檢索 GET 參數?

Patricia Arquette
發布: 2024-12-15 17:22:10
原創
297 人瀏覽過

How to Access and Retrieve GET Parameters in JavaScript?

在 JavaScript 中存取 GET 參數

可以使用 window.location 物件在 HTML 頁面的 JavaScript 中擷取 GET 參數。若要取得不帶問號的GET 參數,請使用以下程式碼:

1

window.location.search.substr(1)

登入後複製

例如,給定URL:

1

http://example.com/page.html?returnurl=%2Fadmin

登入後複製

上面的程式碼將輸出:

1

returnurl=%2Fadmin

登入後複製

函數的替代方法

建立函數擷取特定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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板