简体   繁体   中英

Set an url globally in JavaScript

In an ASP.NET MVC application, we call web service and web API methods from JavaScript files. Whenever the url gets changed, we have to modify the url in many .js files.

As we access the url in JavaScript, is there anyway to set it globally like web.config in .NET?

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),然后在配置中声明此变量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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