如何使JS了解应用程序的根? [英] How do I make JS know about the application root?
问题描述
我有一些JavaScript代码的引用 /职位/ GetIndex
在MVC项目。当我在本地运行这个伟大的工程,因为我有一个控制器
名为 JobsController
。当我部署它,我将应用程序部署到一个乔布斯子文件夹,这意味着该URL应该成为的http://网站/职位/岗位/ GetIndex
,但它会的http://网站/就业/ GetIndex
,我presume因为JavaScript不知道什么叫根URL是,并使用该网站的根。我怎样才能得到它在两种环境下工作?
I have some javascript that's referencing /jobs/GetIndex
in an MVC project. This works great when I run it locally because I have a Controller
called JobsController
. When I deploy it, I deploy the application to a 'Jobs' subfolder, which means the URL should become http://site/jobs/jobs/GetIndex
but it's going to http://site/jobs/GetIndex
, I presume because the javascript doesn't know what the 'root URL' is, and uses the site as the root. How can I get it to work in both environments?
推荐答案
您可以使用 Url.Content
辅助方法,在你的Razor视图生成的URL应用基地,把它分配给一个JavaScript变量和使用,在你的其他的js code来构建其他URL。
始终确保这样做时,使用JavaScript命名空间,以避免与全局JavaScript变量可能存在的问题。
You may use the Url.Content
helper method in your razor view to generate the url to the app base, assign it to a javascript variable and use that in your other js code to build your other urls.
Always make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.
如果你想获得url到具体的操作方法,你可以使用 Url.Action
或 Url.RouteUrl
helper方法。
If you want to get url to a specific action method, you may use the Url.Action
or Url.RouteUrl
helper methods.
因此,在您的Razor视图(布局文件或特定的VIE 的W),你可以做到这一点。
So in your razor view (Layout file or specific view), you may do this.
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '@Url.Content("~")';
myApp.Urls.jobIndexUrl= '@Url.Action("GetIndex","jobs")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
而在你的 PageSpecificExternalJsFile.js
文件,你可以像
var urlToJobIndex= myApp.Urls.jobIndexUrl;
// Or With the base url, you may safely add the remaining url route.
var urlToJobIndex2= myApp.Urls.baseUrl+"jobs/GetIndex";
这里差不多了详细的解答,但在特定的网页/视图使用此
Here is a detailed answer about the same , but using this in a specific page/view
角的js
您可能需要在你的角度控制器/服务/ directives.The同样的方法正确的相对URL(S)会为你的角度code正常工作。简单地建立JS命名对象,并使用角值
提供商将数据传递到你的角度控制器/服务/指令作为解释<一个href=\"http://stackoverflow.com/questions/34427447/angularjs-directive-templateurl-doesnt-work-while-template-works/34427511#34427511\">in这个帖子与例如code细节。
You might need the correct relative url(s) in your angular controller / services / directives.The same approach will work for your angular code as well. Simply build the js namespace object and use the angular value
provider to pass the data to your angular controllers/services/directives as explained in this post in detail with example code.
这篇关于如何使JS了解应用程序的根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!