Thursday, October 13, 2016

Add Base URLs to Grails Page and Scripts

Sometimes we are note sure about final deployment context root address, so the root of the application can be something like mydomain.com/ or mydomain/myapp/ .

Grails or most of the other web app frameworks handle the link creation for such situation with some link facility in pages, but the problem is links in JavaScript, like base url for ajax call or resource loaders.

One possible solution is finding the base urls using the same facility of the framework and set them in global javascript variables.

The best location to add them and complying DRY is the layout page, where all pages have access.

The following is a sample for grails framework to have the url of the root of the app and the assets as well.


window.grails = {
    baseUrl: '${raw(g.createLink(absolute:true, uri:"/"))}'
    assetsUrl : '${ raw(asset.assetPath(src: '')) }',
};


It can be used like this:

$.ajax({
    type: 'GET',
    url: window.grails.baseUrl + 'controller/show/' + id +'.json',
    contentType: 'application/json',
    success: function( data, textStatus, jqXHR )
    {
    },
    error: function( jqXHR, textStatus, errorThrown )
    {
    }
});

No comments: