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.
jQuery ajax() Method. The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends asynchronous HTTP requests to the server.
The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.
The $. ajax() Function. The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .
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;
}
})
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;
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With