dev.e.loper
dev.e.loper

Reputation: 36044

Can I specify relative URL when using jQuery.get?

I'm trying to make an ajax call like so:

 $.get('/home/myInfo', function (data)

     {

        ....

     });

I'm calling it from a page that is at: http://localhost/myapp/home/index

When I try to make the above call, it goes to: http://localhost/myapp/home/index/home/myInfo

I want it to go to http://localhost/myapp/home/myInfo

Do I have to specify absolute URL?

Upvotes: 5

Views: 3755

Answers (2)

streetlogics
streetlogics

Reputation: 4730

Are you sure you have copied and pasted the code correctly? Because as you have it, that should be referencing http://localhost/home/myInfo . The only reason I could see it doing as you have described is if your code was using a relative url like this:

 $.get('home/myInfo', function (data)

     {

        ....

     });

Otherwise, if you're truly using the value "/home/myInfo" instead of "home/myInfo" , you already are referencing the absolute version of the url (the definition of an "absolute" url being that it starts with "/"). I ran some quick tests, and on my local machine, using "/home/myInfo" yields an XHR request to http://localhost/home/myInfo

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

Absolutely never hardcode urls like this in an ASP.NET MVC application. Always use URL helpers when dealing with urls, like this:

$.get('@Url.Action("MyInfo", "Home")', function (data) {
    ....
});

or if this is in a separate javascript file where you cannot use server side helpers, well you could for example use HTML 5 data-* attributes on some DOM element tat you are AJAXifying, like a div or something:

<div id="mydiv" data-url="@Url.Action("MyInfo", "Home")">Click me</div>

and then:

$('#mydiv').click(function() {
    $.get($(this).data('url'), function (data) {
        ....
    });
});

or if you are AJAXifying a form or an anchor:

$('#myanchor').click(function() {
    $.get(this.href, function (data) {
        ....
    });
    return false;
});

where the anchor would of course have been generated using helpers:

@Html.ActionLink("click me", "MyInfo", "Home", null, new { id = "myanchor" })

See? No need to hardcode urls. Don't do it as it will break at the very second you modify the pattern of your routes in Global.asax. By following this technique your code will be totally agnostic to any changes of the structure of your routes.

Upvotes: 14

Related Questions