【问题标题】:How to give proper relative link in ajax ?如何在 ajax 中给出正确的相对链接?
【发布时间】:2014-07-08 06:28:28
【问题描述】:

我已经开发了 MVC 应用程序。

我已在 IIS 上发布它,我的应用程序中很少有无法正常工作的 ajax 方法。

喜欢,

http://demo.mycompanyname.in/Product/getProductDetails/?Id=1638

现在,上面的方法不起作用。

我使用下面的方法来调用上面的方法。

 function getProductDetails(productCode, Index) {
        $.ajax({
            url: "/Product/getProductDetails/",
            data: { Id: productCode },

            dataType: "json",
            success: function (result) {
            }

如果我通过将 'myapp' 我的应用程序名称手动更改 URL, (通过在地址栏中输入)它可以工作......

http://demo.mycompanyname.in/myapp/Product/getProductDetails/?Id=1638

我必须对 ajax 调用方法进行哪些更改?

这个我也试过了……

 url: "~/Product/getProductDetails/",

这也行不通……

【问题讨论】:

  • above method didnt work. 你在控制台看到错误了吗?

标签: ajax model-view-controller


【解决方案1】:

如果你在剃刀视图中试试这个:

$.ajax({
    url: '@Url.Action("getProductDetails","Product")'
    ...

如果您在外部 js 文件中。在 _Layout.cshtml 中定义根 url,如下所示:

<script>
    var app_root = '@Url.Content("~/")'
</script>

并在你的 ajax 中使用它:

$.ajax({
    url: app_root + "/Product/getProductDetails/",    
    ...

或者再次在你的 _Layout.cshtml 中你可以写一个 url.resolve 方法:

<script type="text/javascript">
        Url =
        function () { }
        Url.prototype = {
            _relativeRoot: '@Url.Content("~/")',
                // create an extension method called "resolve"
                resolve: function (relative) {
                    var resolved = relative;
                    if (relative.charAt(0) == '~')
                        resolved = this._relativeRoot + relative;
                    return resolved;
                }
            }
    $Url = new Url();
</script>

和 ajax:

$.ajax({
    url: $Url.resolve("Product/getProductDetails"),    
    ...

毕竟,您的项目脚本将独立于子文件夹工作。

【讨论】:

    猜你喜欢
    • 2018-03-03
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多