我知道URL的查询字符串中的+
代表一个空格。在查询字符串区之外也是这种情况吗?也就是说,执行以下URL:
http://a.com/a+b/c
实际表示:
http://a.com/a b/c
(因此,如果它实际上应该是一个+
,则需要进行编码),或者它实际上表示a+b/c
吗
发布于 2016-10-28 03:00:28
在一个上下文中,空格字符只能编码为"+“:application/x-www-form-urlencoded
键-值对。
RFC-1866 (HTML2.0规范),第8.2.1段,第1节说:“表单字段名称和值被转义:空格字符被"+”替换,然后保留字符被转义“)。
这是一个例子,在URL中,RFC-1866允许将空格编码为加号:"http://example.com/over/there?name=foo+bar"。那么,只有在"?“之后,空格才能被加号替换(在其他情况下,空格应该编码为"%20")。这种编码表单数据的方式也在后来的HTML4.01规范中给出,例如,在HTML4.01规范中查找关于application/x-www-form-urlencoded
的相关段落,等等。
但是,因为很难总是正确地确定上下文,所以最好的做法是永远不要将空格编码为"+“。最好对RFC-3986第2.3页中定义的除"unreserved“之外的所有字符进行百分比编码。下面是一个代码示例,说明了应该编码的内容。它是用Delphi (pascal)编程语言提供的,但对于任何程序员来说,无论使用哪种语言,都很容易理解它的工作原理:
(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const
HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
I: Integer;
c: AnsiChar;
begin
// percent-encoding, see RFC-3986, p. 2.1
Result := S;
for I := Length(S) downto 1 do
begin
c := S[I];
case c of
'A' .. 'Z', 'a' .. 'z', // alpha
'0' .. '9', // digit
'-', '.', '_', '~':; // rest of unreserved characters as defined in the RFC-3986, p.2.3
else
begin
Result[I] := '%';
Insert('00', Result, I + 1);
Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
Result[I + 2] := HexCharArrA[Byte(C) and $F];
end;
end;
end;
end;
function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
Result := UrlEncodeRfcA(Utf8Encode(S));
end;
发布于 2015-01-16 14:23:49
使用encodeURIComponent函数修复url,适用于浏览器和node.js
res.redirect("/signin?email="+encodeURIComponent("aaa+bbb-ccc@example.com"));
> encodeURIComponent("http://a.com/a+b/c")
'http%3A%2F%2Fa.com%2Fa%2Bb%2Fc'
发布于 2014-01-24 06:50:48
请在下面进行尝试:
<script type="text/javascript">
function resetPassword() {
url: "submitForgotPassword.html?email="+fixEscape(Stringwith+char);
}
function fixEscape(str)
{
return escape(str).replace( "+", "%2B" );
}
</script>
https://stackoverflow.com/questions/1005676
复制相似问题