[Javascript] encodeURIComponent()方法


在vue項目中使用vue-router通過url進行傳值

encodeURIComponent

encodeURIComponent() 函數可把字符串作為 URI 組件進行編碼。encodeURIComponent(URIstring)

this.alert = LayDialog.alert({
            content: str,
            okTheme: 'alink',
            title: '您有一筆充值訂單待支付',
            okText: '查看詳情',
            theme: 'ios',
            effect: 'slide',
          }).then(() => {
            this.$router.push(
              {
                path: 'Rechargebill',
                query: {
                  dataObj: encodeURIComponent(JSON.stringify(res.data)),
                }
              }
            );
          });

數據

dataObj=%7B"icon"%3A"http%3A%2F%2Fwww.baidu.com%2Fpubd","status"%3A"pending","way_name"%3A"建設銀行轉賬","pay_type"%3A"bank","amount"%3A"11.00","username"%3A"bianlang3","remark"%3A"","orderno"%3A"OOVINU2931542","dateline"%3A"1555163311","extension"%3A%7B"receiver"%3A%7B"id"%3A"25","name"%3A"建設銀行轉賬","account"%3A"685412266541223","person"%3A"張三"%7D,"transfer"%3A%7B"bank"%3A"","account"%3A"","person"%3A"張三"%7D%7D,"type"%3A"pending"%7D

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

decodeURIComponent

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

let objparse = JSON.parse(decodeURIComponent(this.$route.query.dataObj))

encodeURI()

encodeURI()可以對URI進行編碼,以便發送給瀏覽器。有效的URI中不能包含某些字符,例如空格。而這URI編碼方法就可以對URI進行編碼,它們用特殊的UTF-8編碼替換所有無效的字 符,從而讓瀏覽器能夠接受和理解。

encodeURI()主要用於整個URI(例如,http://www.baidu.com/index.html),而encode-URIComponent()主要用於對URI中的某一段(例如前面URI中的index.html)進行編碼。

encodeURI()和encodeURIComponent()區別

  • encodeURI()不會對本身屬於URI的特殊字符進行編碼,例如冒號、正斜杠、問號和井字號;而encodeURIComponent()則會對它發現的任何非標准字符進行編碼。

  • 使用encodeURI()編碼后的結果是除了空格之外的其他字符都原封不動,只有空格被替換成了%20。而encodeURIComponent()方法則會使用對應的編碼替換所有非字母數字字符。

  • encodeURI()對基礎URL進行編碼,encodeURIComponent()對查詢字符串參數進行編碼

所以這就是對整個URI使用encodeURI(),對附加在現有URI后面的字符串使用encodeURIComponent()的原因。

tips

URI: Uniform ResourceIdentifiers,通用資源標識符


免責聲明!

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



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