When js processes json data returned by the api, it prompts a Unexpected token ILLEGAL error. In this case, it is easy to directly output js and find that there is a line break.
It is a matter of sauce. An interface returns JSON data, and I will handle it and return it to page JS. However, JS reported this error when processing JSON: Unexpected token ILLEGAL, resulting in suspension.
I tried it on the Internet, so I summarized it.
The returned result is about the sauce:
| The Code is as follows: |
Copy code |
|
{"Status": "1", "info": {"date": "2013-12-01", "content": "1. Test content 1
2. Test content 2
3. Test content 3
4. Test content 4
5. Test content 5 "}} |
The preceding error will be reported if it is directly integrated. But it is not appropriate to remove the line feed directly, so it is like this:
| The Code is as follows: |
Copy code |
|
$ Response = ~ S/r/\ r/g;
$ Response = ~ S/n/\ n/g; |
That is to say, convert the line feed in the returned result to "\ r \ n" to the JS, and then the JS receives the rn.
I have tested the processing of json classes and have not found any. Unexpectedly, the final processing is indeed so simple:
The background code replaces the line break rn with \ r \ n. The character received by the front-end code js is rn.
| The Code is as follows: |
Copy code |
|
Public static string ConvertFromListTojson <T> (IList <T> list, int total, string columnInfos) where T: class
{
String [] cols = columnInfos. Split (new char [] {','}, StringSplitOptions. RemoveEmptyEntries );
StringBuilder sb = new StringBuilder (300 );
Sb. Append ("{" total ":");
Sb. Append (total );
Sb. Append ("," rows ":");
Sb. Append ("[");
Foreach (T t in list)
{
Sb. Append ("{");
Foreach (string col in cols)
{
String name = "" {0} ":" {1 }",";
String value = getValue <T> (t, col );
Value = value. Replace ("rn", "\ r \ n ");
Sb. Append (string. Format (name, col, value ));
}
If (cols. Length> 0)
{
Int length = sb. Length;
Sb. Remove (length-1, 1 );
}
Sb. Append ("},");
}
If (list. Count> 0)
{
Int lengh2 = sb. Length;
Sb. Remove (leng22-1, 1 );
}
Sb. Append ("]");
Sb. Append ("}");
Return sb. ToString ();
}
Private static string getValue <T> (T t, string pname) where T: class
{
Type type = t. GetType ();
PropertyInfo pinfo = type. GetProperty (pname );
If (pinfo! = Null)
{
Object v = pinfo. GetValue (t, null );
Return v! = Null? V. ToString ():"";
}
Else
{
Throw new Exception ("nonexistent attribute" + pname );
}
} |