DIV CSS 佈局教程網

用 JavaScript 解析 QueryString 取得 GET 參數
編輯:JavaScript綜合知識     

要在前端讀取網址上的查詢參數,最直觀的做法是切字串。這裡把它封裝成一個小物件,先在初始化時把 ?a=1&b=2 解析成鍵值對存起來,之後就能用方法取值,不必每次都重新解析。

頁面結構範例

<div id="page">
<select name="select1" id="select-type">
  <option value="0">請選擇</option>
  <option value="1">企業</option>
  <option value="2">產品</option>
</select>
</div>

QueryString 物件

QueryString = {
    data: {},
    Initial: function () {
        var aPairs, aTmp;
        var queryString = new String(window.location.search);
        queryString = queryString.substr(1, queryString.length);   // 去掉 "?"
        aPairs = queryString.split("&");
        for (var i = 0; i < aPairs.length; i++) {
            aTmp = aPairs[i].split("=");
            this.data[aTmp[0]] = aTmp[1];
        }
    },
    GetValue: function (key) {
        return this.data[key];
    }
};

$(function () {
    QueryString.Initial();               // 初始化

    var type = QueryString.GetValue("type");
    if (typeof (type) != "undefined") {
        $("#select-type").val(type);     // 用參數值回填下拉選單
    }

    $("#select-type").bind("change", function () {
        var row = $(this).find("option:selected").val();
        if (row == 1) location.href = "?type=" + row;
        if (row == 2) location.href = "?type=" + row;
    });
});

應用情境很典型:使用者從列表頁帶著 type 參數進來,頁面據此把下拉選單設成正確的選項;使用者切換選單時改寫網址,重整後仍維持狀態。

這份實作的幾個缺點

值未做解碼。若參數值含有 %E4%B8%AD 這類編碼,直接取用會得到編碼後的字串。應加上 decodeURIComponent(aTmp[1])。

值中含有 = 時會被截斷。split("=") 遇到 ?url=https://x.com?a=1 這種未編碼的值會切錯。應限制切分次數,或改用 indexOf 定位第一個等號。

未處理無值的參數。?debug 這種只有鍵沒有值的寫法,會讓 aTmp[1] 為 undefined。

change 中的兩個 if 可以合併。row 為 1 或 2 時做的事完全一樣,直接寫 location.href = "?type=" + row; 即可。

現代寫法:URLSearchParams

上述所有邊界條件,瀏覽器原生的 URLSearchParams 都已經處理好了:

const params = new URLSearchParams(location.search);

const type = params.get('type');          // 取值,不存在回傳 null
const has  = params.has('type');          // 判斷是否存在
const all  = params.getAll('tag');        // 同名參數取全部

// 回填下拉選單
if (params.has('type')) {
    $('#select-type').val(params.get('type'));
}

// 修改參數並更新網址(不重新載入)
params.set('type', newType);
history.replaceState(null, '', '?' + params.toString());

// 遍歷所有參數
for (const [key, value] of params) {
    console.log(key, value);
}

URLSearchParams 自 2018 年起已在所有主流瀏覽器(含 IE 之外的 Edge)完整支援,自動處理編碼解碼、重複鍵、空值與特殊字元,且可與 URL 物件搭配讀寫整個網址。新專案沒有理由再手寫字串切分。若要更新網址而不刷新頁面,用 history.replaceState(不新增歷史紀錄)或 pushState(可返回上一狀態)即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved