Today in the project encountered a problem, the data on the page suddenly show no, after the inspection of the JSON data is a problem. When using JSON to transfer data from the background to the foreground, when the data itself contains some special characters, the parsing of the JSON data can be faulted. If the content itself contains "\" "double quotes," \ r \ n "Carriage return line, the parsing of the data will be problematic.
The difference between \r,\n,\r\n
?
1234 |
\n是换行,英文是New line,表示使光标到行首 \r是回车,英文是Carriage return ,表示使光标下移一格 \r\n表示回车换行 |
The difference between "\ r \ n" and "</br>"
?
12 |
\r\n是输出的HTML代码换行(查看html代码时,代码换行了) <br />输出给浏览器换行(看网页效果时,文字换行了) |
When the user enters the content in the textarea, sometimes enters the double quotation mark, the carriage return or the newline character, when saves, these special symbols also also the text content saves in the database, when obtains this data, the JSON parsing will be wrong
The following are problematic data:
?
12345678 |
{
"employees"
: [
{
"firstName"
:
"Bill" ,
"lastName"
:
"Gates”" },
{
"firstName"
:
"George
回车了" ,
"lastName"
:
"Bush" },
{
"firstName"
:
"Thomas" ,
"lastName"
:
"Carter" }
]
}
|
How can you upload data to a page without altering the data? The idea is the back end of the \ r \ n (carriage return) to <br/>, front-end and then <br/> back to \ r \ n
C # code:
1 public static string Encodetextareachar (String str) 2 {3 if (str = = null) return null;4 return str. Replace ("\" "," \\\ "). Replace ("\ r \ n", "<br/>"). Replace ("\ n", "<br/>"). Replace ("\ R", "<br/>"); 5 }
JavaScript code
1 function Encodetextarea (str) {2 str = str.replace (/</g, "<"). Replace (/>/g, ">"); 3 var str = str.replace (/<br\/>/g, "\ r \ n"); 4 return str;5 }
Both languages have the replace () method, and they are slightly different,
The replace of JavaScript is replaced only once, such as "ABCAEBACD" has two C, it only replaces the first, replace ("C", "s"), the result is "ABSAEBACD"
Replace All of the C # replacement ("C", "s"), and the result is "ABSAEBASD"
Note: For Javascript to implement all substitutions, you can replace (/c/g, "s"),//between the contents to be replaced, and g as the global flag
?
123 |
为什么要加这一个呢? str.replace(/</g, "<" ).replace(/>/g, ">" ); 因为后端传过来的 <br/> 变成了 <br/> |
Special character handling in JSON data