1

所以,我正在做一个像这样的普通 ajax 调用:

$.ajax({
    type: "GET",
    url: this.Controller + "/" + this.Action,
    data: data,
    cache: false,
    dataType: "json",
    success: function (data) {
        var json = $.parseJSON(data);
        $("#Debug").html(JSON.stringify(json, undefined, 4));
    },
    error: function (jqXHR, textStatus, errorThrown) {
        var errorMessage = "Unable to retrieve data."
        if (jqXHR.responseText != null) {
            errorMessage += "\n\nError Message: " + jqXHR.responseText;
        }
        alert(errorMessage);
    }
});

当我为 ajax url 使用相对路径时,只要当前页面的 url 中没有 url 变量,它就可以正常工作。它将正确地转到http://domain.com/controller/action

如果有 url 变量,则 ajax url 会尝试 hit http://domain.com/controller/controller/action,但不存在。

如果我像这样添加斜杠:

url: "/" + this.Controller + "/" + this.Action

这解决了 url 变量导致的问题,但仅限于本地。当我部署到我们的服务器时,我的应用程序位于一个子目录中,所以 url 是http://domain.com/myapp. 斜杠解决方案不能像 root ishttp://domain.com和 not那样工作http://domain.com/myapp

4

2 回答 2

0

你可以试试这个$.ajax({url: document.domain + this.Controller ... })

于 2016-03-16T13:28:52.710 回答
0

我尝试了各种通过 JS 执行此操作的方法,但它们都不适用于服务器(带有子目录)和本地(没有)。

所以,我的解决方案是在我的 web.config 的 appsettings 中添加子目录的名称。在主 web.config 中,我有:<add key="Subdirectory" value="" />

在 web.release.config 中,我有:<add key="Subdirectory" value="SubDirectoryName" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />

通过在 web.config 中将其留空并在 web.release.config 中进行设置,子目录将仅在发布到服务器时进行转换和设置。

在 _Layout.cshtml 页面上,我有:

<script> var subdirectory = '@ConfigurationManager.AppSettings["Subdirectory"]'; if (subdirectory != '') { subdirectory = '/' + subdirectory; } </script>

然后,在我试图进行 ajax 调用的 JS 中的任何地方,我将 url 设置为:

url: subdirectory + "/" + this.Controller + "/" + this.Action, // subdirectory comes from _Layout.cshtml

于 2016-03-17T18:06:03.700 回答