It was a small mistake, but it took a lot of time to troubleshoot, so write it down and share it with you.
Cause
Through Ajax dynamic from the background to read the article content, and displayed on the page, loaded into an article, reported JavaScript syntax error, unable to display the article content.
The data format returned by Ajax reading from the background is JSON, using the Newtonsoft.json library to assemble the JSON.
Analysis Reason
Because other articles can load normally, only one article reports JavaScript syntax errors, so you can roughly determine the exception that is caused by the content of the article. Paste the article into the WordPad carefully find, found that there are a few small black squares, manually remove the few small black squares, loading normal.
Copy this block into the program, in the Bigendianunicode encoding (note: JavaScript encoding format is UCS-2, and Bigendianunicode compatible) to convert to a byte array, write to the console, the program and the results are as follows:
public void Test1 () { string str = @ "?"; byte[] bytes = Encoding.BigEndianUnicode.GetBytes (str); foreach (Byte b in bytes) { Console.Write (b.tostring ("X2"));} }
The result is: 2028
Online query learned that this encoding of 2028 characters is the line delimiter, will be interpreted by the browser as a newline, and in JavaScript string expression is not allowed to wrap, resulting in an error.
Workaround
To replace the special character escape, the code looks like this:
str = str. Replace ("\u2028", "\\u2028");
After the replacement, use the previously problematic article test, load normal, problem solved.
In addition, there are 13 special characters in JavaScript, which are recommended to be escaped, as follows:
Unicode Character Value |
Escape Sequences |
meaning |
category |
\u0008 |
\b |
Backspace |
|
\u0009 |
\ t |
Tab |
Blank |
\u000a |
\ n |
newline character (line feed) |
Line Terminator |
\u000b |
\v |
Vertical tab |
Blank |
\u000c |
\f |
Page change |
Blank |
\u000d |
\ r |
Enter |
Line Terminator |
\u0022 |
\" |
Double quotation marks (") |
|
\u0027 |
\‘ |
Single quotation mark (') |
|
\u005c |
\\ |
Back slash (\) |
|
\u00a0 |
|
Non-breaking spaces |
Blank |
\u2028 |
|
Row delimiter |
Line Terminator |
\u2029 |
|
Paragraph separator |
Line Terminator |
\ufeff |
|
BYTE order mark |
Blank |
Extended Reading
- JavaScript special character escaping character comparison table.
- The encoding format used by JavaScript can be seen in this article: Unicode and JavaScript.
- Why can't the results returned by the JSON library be parsed correctly by JavaScript?
- Javascript parse error on ' \u2028 ' Unicode character.
- Example of a JSON library handling special characters used by javascript: Json-js.
JavaScript script exceptions due to special character \u2028