When you use JS to submit data, especially Chinese characters, you often need to URL encode the string to be submitted. There are several URL encoding methods for strings in JS: encodeURI, encodeURIComponent, and escape. In many of the code I see, the escape function is the most used, but this function is not recommended. Let's take a look at these functions:
EncodeURI: URL encoding of the specified string, excluding the key characters in: #/\=.
EncodeURIComponent: encode the characters in the string, including special characters in the URL.
Escape: This is a function in earlier versions of JS. This function has some problems when handling unicode characters.
The Code is as follows:
Copy codeThe Code is as follows:
Var url = "http://www.abc.com? Q = aa & amp; B = haha ";
Var encodedUrl = encodeURI (url );
Alert (encodedUrl); // output: http://www.abc.com? Q = aa & B = % E5 % 91% B5 % E5 % 91% B5
EncodedUrl = encodeURIComponent (url );
Alert (encodedUrl); // output: http % 3A % 2F % 2Fwww.abc.com % 3Fq % 3Daa % 26b % 3D % E5 % 91% B5 % E5 % 91% B5
Alert (escape (url); // output: http % 3A // www.abc.com % 3Fq % 3Daa % 26b % 3D % u5475 % u5475
As shown above, when processing Chinese characters in the escape function, it will be converted to % uxxxx. Obviously, this is different from the URL encoding format, and the encodeURIComponent function encoding is the most thorough, if there is no special need, the encodeURIComponent function is quite common. Of course, it won't be a problem if we use escape. Maybe your server language can be parsed normally, however, this function is not very standard when handling unicode characters. Therefore, we recommend that you use encodeURIComponent and decodeURIComponent to encode and decode the strings.