根 url javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6891920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:14:25  来源:igfitidea点击:

root url javascript

javascriptasp.netasp.net-mvcajax

提问by Rachid

I'm working on an .Net ASP MVC razor application

我正在开发一个 .Net ASP MVC razor 应用程序

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"

回答by Arnis Lapsa

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 对象。

回答by Mrchief

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

回答by Shadow Wizard is Ear For You

What about this?

那这个呢?

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

Does it give correct root URL?

它是否提供了正确的根 URL?

回答by Mariano Quevedo

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

它适用于我的机器和服务器。希望能帮助到你