What is the best way to set up base url for ajax request using Jquery?

Viewed 35740

Since phonegap is based on local html file it doesn't know about base url of remote server. I wonder what is the best way to set base url for ajax requests using jquery? Could anybody provide link to sample?

Currently i think about using jquery ajax prefilter.

5 Answers

Remove leading slash to make ajax url relative to base defined in header.

<head>
    <base href="http://base.com/">
</head>
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        settings.url = settings.url.replace(/^\//,'')
    }
})

You can also place a check to skip urls starting with http (probably cross-domain urls).

Make sure to place it right after including the jQuery file and before all ajax calls.

const baseUrl = 'http://example.com/sub/directory';

$.ajaxSetup({
  beforeSend: function(xhr, options) {
     if( options.url.indexOf('http') !== 0 ) {
        options.url = baseUrl + options.url;
     }
  }
});
Related