简体   繁体   English

在JavaScript中全局设置网址

[英]Set an url globally in JavaScript

In an ASP.NET MVC application, we call web service and web API methods from JavaScript files. 在ASP.NET MVC应用程序中,我们从JavaScript文件调用Web服务和Web API方法。 Whenever the url gets changed, we have to modify the url in many .js files. 每当更改URL时,我们都必须在许多.js文件中修改URL。

As we access the url in JavaScript, is there anyway to set it globally like web.config in .NET? 当我们使用JavaScript访问url时,是否像.NET中的web.config一样全局设置它?

Thanks. 谢谢。

You can just have this or something similar in your view: 您可以在视图中看到以下内容或类似内容:

<script>
  window.apiUrl = '<%=ConfigurationManager.AppSettings["apiUrl"]%>';
</script>

(or if it's Razor?...) (或者如果是剃刀?...)

<script>
  window.apiUrl = '@(ConfigurationManager.AppSettings["apiUrl"])';
</script>

That way, your other scripts can simply reference: 这样,您的其他脚本可以简单地引用:

var url = window.apiUrl;

您可以在视图中声明全局变量(在Controller中调用VewBag),然后在配置中声明此变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM