JavaScript encodeURI 和encodeURIComponent_javascript技巧

來源:互聯網
上載者:User

encodeURI和encodeURIComponet函數都是javascript中用來對URI進行編碼,將相關參數轉換成UTF-8編碼格式的資料。URI在進行定位跳轉時,參數裡面的中文、日文等非ASCII編碼都會進行編碼轉換。

這兩個函數功能上面比較接近,但是有一些區別。

 encodeURI:不會進行編碼的字元有82個 :!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
 encodeURIComponent:不會進行編碼的字元有71個:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

問題:

  ajax.get ( url+'?k1'=v1+'&k2'=v2+'&k3'=v3, ... ); 

  由於URL只進行了encodeURI編碼,所以想提交的參數有searchWord = a+b時,變成了a b。 

解決辦法: 

  ajax.post( url, params,....) 

  其中params是對象。 

  原因:如果參數是對象或數組時,組件庫已經幫你進行encodeURIComponent了。 而如果你僅僅是字串,組件庫什麼也沒做,所以到後端時就把特殊字元給過濾了。 

  encodeURI()用法

  該方法不會對 ASCII 字母和數字進行編碼,也不會對這些 ASCII 標點符號進行編碼: - _ . ! ~ * ' ( ) 。 

  該方法的目的是對 URI 進行完整的編碼,因此對以下在 URI 中具有特殊含義的 ASCII 標點符號,encodeURI() 函數是不會進行轉義的:;/?:@&=+$,# 

  提示:如果 URI 組件中含有分隔字元,比如 ? 和 #,則應當使用 encodeURIComponent() 方法分別對各組件進行編碼。

  例子:

document.write(encodeURI("http://www.w3school.com.cn")+ "<br />") document.write(encodeURI("http://www.w3school.com.cn/My first/")) document.write(encodeURI(",/?:@&=+$#")) //批註:只轉換網域名稱後面的部分,並且對,/?:@&=+$#不處理。 // http://www.w3school.com.cn // http://www.w3school.com.cn/My%20first/ // ,/?:@&=+$#  

  decodeURI() 函數可對 encodeURI() 函數編碼過的 URI 進行解碼。

  encodeURIComponent()用法 

  該方法不會對 ASCII 字母和數字進行編碼,也不會對這些 ASCII 標點符號進行編碼: - _ . ! ~ * ' ( ) 。 

  其他字元(比如 :;/?:@&=+$,# 這些用於分隔 URI 組件的標點符號),都是由一個或多個十六進位的逸出序列替換的。

  提示:請注意 encodeURIComponent() 函數 與 encodeURI() 函數的區別之處,前者假定它的參數是 URI 的一部分(比如協議、主機名稱、路徑或查詢字串)。因此 encodeURIComponent() 函數將轉義用於分隔 URI 各個部分的標點符號。

  例子:

document.write(encodeURIComponent("http://www.w3school.com.cn")) document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/")) document.write(encodeURIComponent(",/?:@&=+$#")) //對比 // http%3A%2F%2Fwww.w3school.com.cn // http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F // %2C%2F%3F%3A%40%26%3D%2B%24%23  

  decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.