2016-04-26 47 views
3

我想從Javascript中的URL讀取獲取參數。我發現this在Javascript中獲取URL參數不適用於urlencoded'&'

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

有誰知道我該如何解決這個問題?

回答

4

您需要撥打decodeURIComponent並在sParameterName[0]sParameterName[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的評論中提到。

+0

非常感謝!哦,我沒有閱讀Zakinster的評論。一個錯誤在我身邊。 *UPS* – progNewbie