简体   繁体   English

根网址javascript

[英]root url javascript

I'm working on an .Net ASP MVC razor application 我正在研究.Net ASP MVC剃须刀应用程序

The root url on the server being "myWebSite.com/myApp/" 服务器上的根URL为“myWebSite.com/myApp/”

I need to find dynamically this url to have the right url to make some Ajax call to action like this 我需要动态地找到这个url以使用正确的url来执行这样的Ajax调用操作

    $.ajax(
    {
        type: "POST",
        url: root + "/Controller/Action",
        data: ...
    }

I read a few things here and there but what I found doesn't work 我在这里和那里读了一些东西,但我找到的东西不起作用

"document.location.hostname" -> "myWebSite.com"
"location.host"              -> "myWebSite.com"
"window.location.pathname"   -> "/myApp/"

Last one sounded promissing but if I navigate in the website : 最后一个听起来很有意思,但如果我在网站上导航:

 for an url :  "myWebSite.com/myApp/Controller/Action?1" 
 "window.location.pathname"   -> "/myApp/Controller/Action"

In asp.net mvc, using razor view engine, I got this in my layout: 在asp.net mvc中,使用razor视图引擎,我在我的布局中得到了这个:

<script type="text/javascript">
 var baseUrl = "@Url.Content("~")";
</script>

That way we can define application base url as javascript object that is accessible from everywhere. 这样我们就可以将应用程序基本URL定义为可从任何地方访问的javascript对象。

You don't need to find this. 你不需要找到这个。 Use realtive path: 使用实际路径:

    $.ajax(
    {
        type: "POST",
        url: "Controller/Action",
        data: ...
    }

This will go in as <root>/Controller/Action 这将作为<root>/Controller/Action进入

What about this? 那这个呢?

var root = "<%=Request.ApplicationPath%>";
alert(root);

Does it give correct root URL? 它是否提供正确的根URL?

I use this: 我用这个:

In razor: 用剃刀:

Uri auxBaseUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority));
Uri baseUri = new Uri(auxBaseUri, Url.Content("~"));   

Then in the js I use: 然后在js中我使用:

var baseUrl = "@baseUri.ToString()";

$.ajax
({
    type: "POST",
    url: baseUrl + "Controller/Action",
    ...

It works on my machine and on the server. 它适用于我的机器和服务器。 Hope it helps 希望能帮助到你

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

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