通过javascript从代码后面访问变量

时间:2010-04-26 15:10:40

标签: asp.net javascript vb.net json

我有以下代码,我想在javascript中返回变量“t”:

代码背后:

Public Shared Function GetSomeText() As String
  Dim result = "This is from code behind"
  Return result
End Function

javascript中的来电变量:

//This is not working like that, I think
    var t = GetSomeText();

那么,如何让变量“t”从代码隐藏中获取函数GetSomeText的“结果”?

谢谢。

2 个答案:

答案 0 :(得分:12)

试试这个 - 假设这是页面上的公共方法。这将在页面类上调用GetSomeText()方法,然后在呈现页面时对页面执行Response.Write()。结果应该在javascript中的单引号之间结束。

 var t = '<%= GetSomeText() %>';

答案 1 :(得分:2)

您需要将字符串写入服务器端代码中的Javascript变量,如下所示:(在ASPX页面的<script>块中)

var t = "<%= GetSomeText() %>";

请注意,必须正确地转义它,如下所示:(或使用AntiXSS Toolkit

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();
}