What is the best way to set up base url for ajax request using Jquery?
Both of the established answers have major drawbacks. Requiring a function to be called to massage your URL every time you make a request is a lot of extra typing. Adding a base tag to a page works great most of the time, but it causes some trouble if you're doing heavy duty work with SVGs. Here's a simple solution that fixes all your URLs at once without using the base tag.
var baseUrl = 'http://my.hardcoded.url/';
$.ajaxSetup({
beforeSend: function(xhr, options) {
options.url = baseUrl + options.url;
}
})
The semantically correct way of doing this is to use the <base>
tag:
<head>
<base href="http://mydomain.com/">
</head>
Then retrieve the value like this (unfortunately jQuery.ajax() does not pick up this value automatically):
$('head base').attr('href');
Element reference: http://www.w3.org/TR/html4/struct/links.html#edef-BASE