逃脱在C#报价为JavaScript消费 [英] Escape Quote in C# for javascript consumption
问题描述
我有一个以JSON格式返回查询结果的ASP.Net网络处理器
I have a ASP.Net web handler that returns results of a query in JSON format
public static String dt2JSON(DataTable dt)
{
String s = "{\"rows\":[";
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
s += "{";
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
s += "\"" + dr.Table.Columns[i].ToString() + "\":\"" + dr[i].ToString() + "\",";
}
s = s.Remove(s.Length - 1, 1);
s += "},";
}
s = s.Remove(s.Length - 1, 1);
}
s += "]}";
return s;
}
问题是,有时返回的数据有引号它,我需要,以便它可以正确地创建成JS对象JavaScript的转义这些。我需要一种方法来找到报价在我的数据(每一次行情不存在),并放置一个/字符在他们面前。
The problem is that sometimes the data returned has quotes in it and I would need to javascript-escape these so that it can be properly created into a js object. I need a way to find quotes in my data (quotes aren't there every time) and place a "/" character in front of them.
示例响应文本(错误):
Example response text (wrong):
{"rows":[{"id":"ABC123","length":"5""},
{"id":"DEF456","length":"1.35""},
{"id":"HIJ789","length":"36.25""}]}
我需要难逃所以我的反应应该是:
I would need to escape the " so my response should be:
{"rows":[{"id":"ABC123","length":"5\""},
{"id":"DEF456","length":"1.35\""},
{"id":"HIJ789","length":"36.25\""}]}
此外,我pretty新的C#(一般编码真),所以如果其他的东西在我的code看起来傻傻的让我知道。
Also, I'm pretty new to C# (coding in general really) so if something else in my code looks silly let me know.
推荐答案
有关.NET 4.0 +有标准 HttpUtility.JavaScriptStringEn code
For .net 4.0 + there is standard
HttpUtility.JavaScriptStringEncode
对于由孤立codeR前面所述西风的解决方案是相当不错的。
For earlier west wind solution described by Lone Coder is quite nice
这篇关于逃脱在C#报价为JavaScript消费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!