URL passing parameters are common data passing methods. However, if you do not pay attention to them, they are also prone to problems.
The most common problem is that URL transmission contains Chinese garbled characters and spaces are transcoded. The best solution to this problem is to pass the pre-encoding and decode the received data. Encoding we useencodeURI
AndencodeURIComponent
, Decoding.decodeURI
AnddecodeURIComponent
.
Encodeuri () encodes a string into a URI. (Corresponding to decodeuri)
Encodeuricomponent () encodes a string into a URI component.
Decodeuri () decodes an encoded Uri. Corresponding to encodeuri)
Decodeuricomponent () decodes an encoded URI component. (Corresponding to encodeuricomponent)
What are the differences between these two transcoding and decoding methods? You can see the following code execution results:
VaR urlstr = "break"; var enuri = encodeuri (urlstr); var deuri = decodeuri (urlstr); var enuric = encodeuricomponent (urlstr); var deuric = decodeuricomponent (urlstr ); console. log ("Initial URL:" + urlstr); console. log ("encodeuri transcoding:" + enuri); console. log ("decodeuri decoding:" + deuri); console. log ("encodeuricomponent transcoding:" + enuric); console. log ("decodeuricomponent decoding:" + deuric );
Running result:
Initial URL: http://www.coolfish.cn/tag/urlchinese garbled
Encodeuri transcoding: http://www.coolfish.cn/tag/url%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
Decodeuri decoding: http://www.coolfish.cn/tag/urlchinese Garbled text
Encodeuricomponent transcoding: HTTP % 3A % 2f % 2fwww.coolfish.cn % 2 ftag % 2 furl % E4 % B8 % ad % E6 % 96% 87% E4 % B9 % B1 % E7 % A0 % 81
Decodeuricomponent decoding: http://www.coolfish.cn/tag/urlchinese garbled
We can see that the URI will be encoded when the encodeuricomponent is transcoded (the URL contains: // transcoded ).
When our URL is passed with parameters similar to callbackurl, it is best to use encodeuricomponent and decodeuricomponent for encoding and transcoding.
Differences between decodeuri, decodeuricomponent, encodeuri, and encodeuricomponent