Relative URL in JQuery Post Call

前端 未结 7 1836
终归单人心
终归单人心 2021-01-30 17:22

I have the following situation.

I developed my first MVC Asp.Net application. it runs on my server at the following adress

http://localhost:59441/


        
相关标签:
7条回答
  • 2021-01-30 18:17

    @Tommy's answer was a great pointer, however for .NET Core I had to do things a little differently, as the Request object has different properties.

    Things were made more tricky by deploying to a virtual directory but using IIS Express for development; hence the if statement when setting the base url.

    Shared/_Layout.cshtml

    <!-- Set the site root for javascript in _Layout.cshtml.-->
    @if (!String.IsNullOrWhiteSpace(@Context.Request.PathBase.Value))
    {
        /* LIVE - includes virtual directory */
        <script>
            window.siteRoot = "@Context.Request.Scheme" + "://" + "@Context.Request.Host.Value" + "@Context.Request.PathBase.Value" + "/";
        </script>
    }
    else
    {
       /* DEBUG - no virutal directory, e.g. IIS Express */
        <script>
            window.siteRoot = "@Context.Request.Scheme" + "://" + "@Context.Request.Host.Value" + "/";
        </script>
    }
    

    Then from any JavaScript file

    /* from any javascript file */
    var url = window.siteRoot + 'MySearch/GetMySearchResults';
    
    $.ajax({
        url: url,
        type: 'GET',
        cache: false,
        data: searchObj,
        success: function (result) {
            alert('yatta!');
        },
        fail: function (e, k, n) {
            alert('hmph!');
        },
        done: function() {
            // hide spinner
        }
    });
    

    Obviously you might wish to create your own namespace or something to save polluting window. I've tried to keep the example below as simple as possible.

    0 讨论(0)
提交回复
热议问题