您可以将 web.config 中的值序列化为 JSON,并将它们添加到您的 JavaScript 可以读取和解析的 <script type="application/json"> 元素中。
这是我能想到的最精简的例子。您可能希望更好地封装如何从服务器代码编写此代码以及如何从 JavaScript 读取它(并想出更好的名称。)
首先,在您的 web.config 中,定义包含您要传递给 JavaScript 的键/值对的部分:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="jsConfigurationValues"
type="System.Configuration.NameValueSectionHandler" />
</configSections>
<jsConfigurationValues>
<add key="someValue" value="a" />
<add key="apiUrl" value="http://theurl" />
</jsConfigurationValues>
<!-- the rest of your web.config -->
</configuration>
在 web 表单的代码隐藏中是这个函数。
protected string JavascriptConfigurationValues()
{
var configurationValues =
(NameValueCollection)ConfigurationManager.GetSection("jsConfigurationValues");
var dictionary = new Dictionary<string, string>();
foreach(var key in configurationValues.AllKeys)
dictionary.Add(key, configurationValues[key]);
return JsonConvert.SerializeObject(dictionary);
}
在 web 表单的标记中是这样的:
<script type="application/json" id="mySettings">
<% =JavascriptConfigurationValues() %>
</script>
(您可以将其中的部分或全部放在 UserControl 中或以其他方式封装。)
此脚本读取 JSON 并将其分配给变量:
var mySettings = JSON.parse(document.getElementById("mySettings").textContent);
现在可以访问了:
var apiUrl = mySettings.apiUrl;