【发布时间】:2014-11-19 10:21:11
【问题描述】:
我们如何在 web.config 文件中定义一个变量并在 Javascript 代码中使用它?
我尝试分配键值对,但似乎不起作用!
【问题讨论】:
-
您能否向我们展示一些代码,说明您是如何尝试分配它的?
标签: javascript asp.net web.config-transform
我们如何在 web.config 文件中定义一个变量并在 Javascript 代码中使用它?
我尝试分配键值对,但似乎不起作用!
【问题讨论】:
标签: javascript asp.net web.config-transform
您应该通过代码隐藏将变量从 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。
【讨论】:
无法直接从 Javascript 中的 web.config 读取。 web.config 仅在服务器端可用,而 Javascript 将在客户端运行。
【讨论】: