虚拟目录中的Javascript不知道虚拟目录

Dan*_*ann 20 javascript asp.net-mvc jquery virtual-directory

假设我有网站 http:// localhost/virtual 其中virtual是虚拟目录

我有一个使用JQuery在javascript文件中定义的Ajax请求

$.getJSON("/Controller/Action")
Run Code Online (Sandbox Code Playgroud)

调用此方法时,客户端会尝试在根级别找到URL,即 http:// localhost/Controller/Action

如果我添加波浪号(〜)符号,它将变为 http:// localhost/virtual /〜/ Controller/Action

它应该(如果它是我想要的那样)解析为 http:// localhost/virtual/Controller/Action

有想法该怎么解决这个吗?

小智 24

阿库的上面的暗示看起来正确,但它不想为我工作.最后我想出来就像这样使用它

<script type="text/javascript">
    var config = {
        contextPath: '<%= @Url.Content("~")  %>'
    };
</script>
Run Code Online (Sandbox Code Playgroud)

然后在我的JavaScript中我像这样使用它

config.contextPath +'myAppPath".

因此,如果没有虚拟目录,则解析为"/"+"myAppPath",如果是虚拟目录,则解析为"/ VirtualPath /"+ +"myAppPath"

这最终对我有用.


And*_*eas 15

我成功使用了这个解决方案

将以下元素放在母版页中

<%= Html.Hidden("HiddenCurrentUrl", Url.Action("Dummy"))%>
Run Code Online (Sandbox Code Playgroud)

在主javascript文件中声明一个全局变量

var baseUrl = "";
Run Code Online (Sandbox Code Playgroud)

加载javascript时,将baseUrl设置为"HiddenCurrentUrl"的值

baseUrl = $("#HiddenCurrentUrl").val();
baseUrl = baseUrl.substring(0, baseUrl.indexOf("Dummy"));
Run Code Online (Sandbox Code Playgroud)

使用baseUrl

$.getJSON(baseUrl + "Action")
Run Code Online (Sandbox Code Playgroud)

编辑改进的解决方案

在你的控制器中

ViewBag.BaseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "/";
Run Code Online (Sandbox Code Playgroud)

在您的母版页中

<script type="text/javascript">
    var YourNameSpace = YourNameSpace || {};
    YourNameSpace.config = {
        baseUrl: "@ViewBag.BaseUrl"
    }
</script> 
Run Code Online (Sandbox Code Playgroud)

使用你的baseUrl

$.getJSON(YourNameSpace.config.baseUrl + "Action")
Run Code Online (Sandbox Code Playgroud)