【问题标题】:web.config variable declaration and use in javascriptweb.config 变量声明和在 javascript 中的使用
【发布时间】:2014-11-19 10:21:11
【问题描述】:

我们如何在 web.config 文件中定义一个变量并在 Javascript 代码中使用它?

我尝试分配键值对,但似乎不起作用!

【问题讨论】:

标签: javascript asp.net web.config-transform


【解决方案1】:

您应该通过代码隐藏将变量从 web.config 传递到 JS 文件。例如,假设您的变量名为my-variable。你的 web.config 应该是这样的:

<configuration>
 <appSettings>
    <add key="my-variable" value="my-value" />
  </appSettings>
</configuration>

您的 aspx 文件可以像这样获取它并将其发送给 JS:

protected void Page_Load(object sender, EventArgs e) {
    ClientScriptManager csm = Page.ClientScript;
    Type cstype = this.GetType();
    string myVariable = ConfigurationManager.AppSettings["my-variable"].ToString();

    // Add a script for the current page just before the end tag </form>
    csm.RegisterStartupScript(cstype, 
        "InitVariable", 
        String.Format("window.myVariable = '{0}';", myVariable, true);
}

然后对于任何JS,你都可以使用这个变量myVariable

【讨论】:

    【解决方案2】:

    无法直接从 Javascript 中的 web.config 读取。 web.config 仅在服务器端可用,而 Javascript 将在客户端运行。

    【讨论】:

      猜你喜欢
      • 2011-12-12
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 2017-09-16
      相关资源
      最近更新 更多