Search code examples
urljquerygetjson

Broken relative Url in jQuery getJSON Ajax Method


The Url for my development environment is:

http://localhost/mysite/blah...

I am using jQuery & getJSON to perform some ajax actions on my site, which work fine all the time I specify the url as:

/mysite/controller/action

..but this is not ideal as I don't want to hardcode my development url into my seperate jQuery include files.

When the site goes live, it'll be fine to have controller/action or /controller/action as the url as that will resolve ok, but for the development site, it's no go.

I've tried:

controller/action

..but this returns a 404, which suprised me as I thought the lack of / at the front of the url would prevent from looking at the website root.

There must be a neat solution to this?


Solution

  • I would do this by inserting a global constant in my HTML header:

    <script type="text/javascript">
      var BASE_URL = '/mysite/';
    </script>
    

    That would be inserted from your server so it can be dynamically changed. Later in your script, you'll be able to make AJAX requests with (jQuery style here):

    $.ajax( BASE_URL + '/controller/action', ...);