对要发送到web服务器的查询字符串进行编码时-何时使用escape(),何时使用encodeURI()或encodeURIComponent():
使用转义符:
escape("% +&=");
OR
使用encodeURI()/encodeURIComponent()
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
受Johann桌子的启发,我决定延长桌子。我想看看哪些ASCII字符被编码。
var ascii=“!\”#$%&'()*+,-/0123456789:;<=>?@EFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvxyz{|}~“;var编码=[];ascii.split(“”).forEach(函数(字符){var obj={char};if(char!=编码URI(char))obj.encodeURI=编码URI(字符);if(char!=encodeURIComponent(char))obj.encodeURIComponent=编码URI组件(字符);if(obj.encodeURI|| obj.encoURIComponent)编码推送(obj);});console.table(编码);
表仅显示编码字符。空单元格表示原始字符和编码字符相同。
另外,我为urlenoder()和rawurlenodes()添加了另一个表。唯一的区别似乎是空格字符的编码。
<script>
<?php
$ascii = str_split(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);
$encoded = [];
foreach ($ascii as $char) {
$obj = ["char" => $char];
if ($char != urlencode($char))
$obj["urlencode"] = urlencode($char);
if ($char != rawurlencode($char))
$obj["rawurlencode"] = rawurlencode($char);
if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))
$encoded[] = $obj;
}
echo "var encoded = " . json_encode($encoded) . ";";
?>
console.table(encoded);
</script>
我建议不要按原样使用这些方法中的一种。编写自己的函数来做正确的事情。
MDN给出了一个很好的url编码示例,如下所示。
var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
console.log(header);
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent