[英]Best way to put user input into generated javascript?
I need for someone to be able to put some text into a page and then this gets sent to the server, saved in the database, and else where this text is put into a javascript variable. 我需要有人能够将一些文本放入页面中,然后将其发送到服务器,保存在数据库中,否则将这些文本放入javascript变量中。
Basically like this: 基本上是这样的:
Write("var myVar=\""+MyData+"\";");
What is the best way of escaping this data? 逃逸此数据的最佳方法是什么? Is there anything out there already to deal with things like
'
and "
and new lines? Is base64 my only option? 难道那里有什么已处理的事情像
'
和"
新线?采用Base64我唯一的选择?
My serverside framework/language is ASP.Net/C# 我的服务器端框架/语言是ASP.Net/C#
You should use WPL : 您应该使用WPL :
Write("var myVar=" + Encoder.JavaScriptEncode(MyData, true) + ";");
if you don't want to reference the library, you can use the following function (adapted from the .Net source): 如果您不想引用该库,则可以使用以下功能(改编自.Net源代码):
public static void QuoteString(this string value, StringBuilder b) {
if (String.IsNullOrEmpty(value))
return "";
var b = new StringBuilder();
int startIndex = 0;
int count = 0;
for (int i = 0; i < value.Length; i++) {
char c = value[i];
// Append the unhandled characters (that do not require special treament)
// to the string builder when special characters are detected.
if (c == '\r' || c == '\t' || c == '\"' || c == '\'' || c == '<' || c == '>' ||
c == '\\' || c == '\n' || c == '\b' || c == '\f' || c < ' ') {
if (b == null) {
b = new StringBuilder(value.Length + 5);
}
if (count > 0) {
b.Append(value, startIndex, count);
}
startIndex = i + 1;
count = 0;
}
switch (c) {
case '\r':
b.Append("\\r");
break;
case '\t':
b.Append("\\t");
break;
case '\"':
b.Append("\\\"");
break;
case '\\':
b.Append("\\\\");
break;
case '\n':
b.Append("\\n");
break;
case '\b':
b.Append("\\b");
break;
case '\f':
b.Append("\\f");
break;
case '\'':
case '>':
case '<':
AppendCharAsUnicode(b, c);
break;
default:
if (c < ' ') {
AppendCharAsUnicode(b, c);
} else {
count++;
}
break;
}
}
if (b == null) {
b.Append(value);
}
if (count > 0) {
b.Append(value, startIndex, count);
}
return b.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.