我们如何在web.config文件中定义变量并在Javascript代码中使用相同的变量?
我尝试分配键值对,但似乎无效!
答案 0 :(得分: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
。
答案 1 :(得分:0)
无法直接从Javascript中的web.config读取。 web.config仅在服务器端可用,而Javascript将在客户端运行。