应用程序网址更改时,请勿更改ajax网址

时间:2015-12-28 09:58:43

标签: jquery ajax asp.net-mvc

我从事MVC项目。我从jquery ajax调用我的ActionResult为

$.ajax({
        url: '@Url.Action("SaveCustomer","Customer")',
        type: 'POST',
        data: JSON.stringify(customerViewModel),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, jqXHR) {
            alert('Customer saved successfully');                 
        }
    });

当代码位于/ cshtml页面时,此代码按预期工作。我想将此代码移动到单独的js文件中。    现在," @ Url.Action"在这里不起作用,所以我将网址替换为' / Customer / SaveCusomer'   当我以下面的格式托管应用程序时,这也很有效:

http://localhost:12345/Customer

但我想主持下面的应用程序

 http://localhost:12345/ApplicationName/Customer

发生了什么,' / Customer / SaveCusomer'没有用。

那么如何使ajax URL与主机URL一起使用

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,并通过在layout.cshtml页面中添加一个全局变量来保存根路径来解决。并在其他地方使用此变量。

<script>
        APPLICATION_PATH = '@Url.Content("~/")';
</script>

在js文件中:

$.ajax({
        type: "POST",
        url: APPLICATION_PATH + "Company/Update",
        data: JSON.stringify(_company),
        contentType: "application/json",
        datatype: 'json',
        success: function (response) {

        },
        error: function (response) {

        }
    });