萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 解析 URL 參數解決中文亂碼:兩種方法完整比較

URL 傳遞中文參數若未編碼/解碼會產生亂碼。本文提供「正則解析法」與「split 迴圈法」兩種取參函式,並示範 encodeURI/decodeURI 正確編解碼流程。

方法一:正則解析法(推薦)

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}
// 使用
var val = getQueryString("參數名");
  • decodeURIComponent 對應 encodeURIComponent,支援完整 Unicode。
  • 正則 i 忽略大小寫。

方法二:split 迴圈法(教學用)

function GetRequest() {
    var url = location.search;
    var theRequest = {};
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
// 使用
var Request = GetRequest();
var param1 = Request["參數1"];

編碼/解碼完整流程

// 傳參頁面
var userName = $("#userName").html();
window.open(encodeURI(url + "?userName=" + userName));

// 接收頁面
var userName = decodeURI(urlInfo.split("?")[1].split("=")[1]);
$("#userName").html(userName);

注意:encodeURI 不編碼 ASCII 字母數字與 ~!@#$&*()=:/,;?+,若參數值包含特殊符號請用 encodeURIComponent。

copyright © 萬盛學電腦網 all rights reserved