簡體   English   中英

在Javascript中獲取URL參數不能與urlencoded'&'一起使用

[英]Get URL-Parameter in Javascript doesn't work with urlencoded '&'

我想從Javascript中的URL讀取一個get參數。 我找到了這個

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

問題是,我的參數是這樣的:

iFZycPLh%Kf27ljF5Hkzp1cEAVR%oUL3 $ MCE&@ * XFcdHBb CRyKkAufgVc32!hUni

我已經制作了urlEncode,所以它是這樣的:

iFZycPLh%25Kf27ljF5Hkzp1cEAVR%25oUL3%24Mce%26%40XFcdHBb * CRyKkAufgVc32!hUni

但是,如果我調用getUrlParameter()函數,我只是得到結果:

iFZycPLh%Kf27ljF5Hkzp1cEAVR%oUL3 $ MCE

有誰知道我怎么解決這個問題?

您需要在sParameterName[0]sParameterName[1]上調用decodeURIComponent ,而不是在整個search.substring(1))search.substring(1))

(即關於它的組成部分

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        var key = decodeURIComponent(sParameterName[0]);
        var value = decodeURIComponent(sParameterName[1]);

        if (key === sParam) {
            return value === undefined ? true : value;
        }
    }
};

zakinster對您鏈接的答案的評論中提到了這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM