GET請求中對於參數中特殊字符的處理


get請求響應為 400,問題在於:{}、\%&,因為有特殊符號所以報錯了。

解決方法:

1、在 拼接 請求URL 之前 可以先將 path參數 的參數值通過 encodeURIComponent 處理一下。例如:

var params = { token:xxx };
for(item in params){
    params[item] = encodeURIComponent(params[item]);
}

2、或用 RegExp 去替代

var reg = new RegExp(/\%/,"g");
var reg1 = new RegExp(/\&/,"g");
var params = { token:xxx };
for(item in params){
    params[item] = String(params[item]).repalce(reg,"%25").replace(reg1,"%25");
}

特殊字符分類

  1. 用於分隔 URI 組件的標點符號:;/?:@&=+$,#
  2. 其他ASCII 標點符號進行編碼: - \_ . ! ~ \* ' ( )

encodeURIencodeURIComponent的區別:

encodeURIComponent:傳遞參數時需要使用encodeURIComponent,這樣組合的url才不會被#等特殊字符截斷。另外,encodeURIComponent只會對用於分隔 URI 組件的標點符號進行處理。不會對其他標點符號進行編碼。

encodeURI:進行url跳轉時可以整體使用encodeURI。
encodeURI():不會對用於分隔 URI 組件的標點符號進行編碼,例如冒號、正斜杠、問號和井字號;
encodeURI():在實踐中更常見的是對查詢字符串參數而不是對基礎URL進行編碼.

 

兼容性比較強的替代版本:

for(var item in params){
    var nowData = params[item];
    try{ 
       params[item] = encodeURIComponent(decodeURIComponent(nowData)) 
    }catch(err){
        var reg = new RegExp(/\%/,"g");
        params[item] = encodeURIComponent(decodeURIComponent(nowData.replace(reg,"%25")))
    }
}
  • 瀏覽器在對%執行decodeURIComponent時報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM