浏览器是否发送“\r\n”或“\n”或者它取决于浏览器?
这个问题困扰了我一百万年......每当我创建一个带有允许多行文本区域的网站(例如用户个人资料的“Bio”)时,我总是最终编写以下偏执的代码:
// C# code sample...
bio = bio.Replace("\r\n", "\n").Replace("\r", "\n");
bio = Regex.Replace(@"\n{2,}", "\n\n");
那么,什么如果 有多行,浏览器是否会发送该内容?
This question has bothered me for a million years... whenever I create a website with a textarea that allows multi-line (such as a "Bio" for a user's profile) I always end up writing the following paranoid code:
// C# code sample...
bio = bio.Replace("\r\n", "\n").Replace("\r", "\n");
bio = Regex.Replace(@"\n{2,}", "\n\n");
So, what do browsers send up for a <textarea name="Bio"></textarea>
if it has multiple lines?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HTTP 和 MIME 规范指定标题行必须以 \r\n 结尾,但它们并不清楚(有些人会认为它们是否清楚)处理 TEXTAREA 的内容。 (例如,参见此帖子来自 HTML 工作组,讨论了该问题。)
以下是 HTTP/1.1 规范中有关消息标头的引用:
我认为这总体上是一个很好的策略:对你生产的东西严格要求,但对你接受的东西宽松。您应该假设您将收到各种行终止符。 (请注意,除了 CRLF 和 LF 之外,Mac OS-9 还单独使用了 CR,并且周围还有一些这样的字符。 Unicode 标准(第 5.8 节)指定了应被识别为行终止符的各种字符序列;有一个列表此处。)
The HTTP and MIME specs specify that header lines must end with \r\n, but they aren't clear (some would argue that it isn't clear if they are clear) about what to do with the contents of a TEXTAREA. (See, for instance, this thread from an HTML working group about the issue.)
Here's a quote from the HTTP/1.1 spec about message headers:
I think that is a good strategy in general: be strict about what you produce but liberal in what you accept. You should assume that you will receive all sorts of line terminators. (Note that in addition to CRLF and LF, Mac OS-9 used CR alone, and there are still a few of those around. The Unicode standard (section 5.8) specifies a wide range of character sequences that should be recognized as line terminators; there's a list of them here.)
所有现代浏览器都会发送 CRLF (
\r\n
)。然而,这并不是一个令人满意的标准化,所以我绝对认为标准化所有多行输入文本的换行符是值得的。当通过 JavaScript 读取值而不是直接从表单提交值时,浏览器行为会有所不同。 IE 和 Opera 返回带有 CRLF 的字符串; Firefox 和 WebKit 返回 LF。因此,使用 JavaScript/XMLHttpRequest 帮助提交的任何表单都可能采用任一形式。
All modern browsers send CRLF (
\r\n
). However this is not something that has been satisfactorily standardised so I would definitely consider it worthwhile to normalise the newlines of all multi-line input text.When the value is read through JavaScript rather than being submitted directly from a form, browser behaviour differs. IE and Opera return strings with CRLFs in; Firefox and WebKit return LF. So any form that gets submitted with JavaScript/XMLHttpRequest help is likely to come in either form.