浏览器是发送“ r n”还是“ n”,还是取决于浏览器?

这个问题困扰了我一百万年... ... 每当我创建一个允许多行文本的网站(比如用户个人资料的“ Bio”) ,我总是以写下面这些偏执的代码告终:

// C# code sample...
bio = bio.Replace("\r\n", "\n").Replace("\r", "\n");
bio = Regex.Replace(@"\n{2,}", "\n\n");

那么,如果 <textarea name="Bio"></textarea>有多行,浏览器会发送什么信息给它呢?

68344 次浏览

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:

The line terminator for message-header fields is the sequence CRLF. However, we recommend that applications, when parsing such headers, recognize a single LF as a line terminator and ignore the leading CR.

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.)

what do browsers send up for a <textarea></textarea> if it has multiple lines?

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.