What is the best way to configure the base url for an ajax request using jQuery?

Since phonegap is based on a local html file, it does not know about the base URL of the remote server. Interestingly, the best way to set the base url for ajax requests using jquery? Can someone provide a link to the sample?

I'm currently thinking of using a jquery ajax prefilter.

+9
source share
4 answers

When I ran into this problem, I simply put this information as a data item in a tag.

<body data-base="http://mydomain.com"> ... 

And then used this to create the correct URL for this request:

  //If pathOrURL is a relative path (eg /users/1), then we return a qualified // URL, such as http://mydomain.com/users/1 // otherwise, we return the URL as is var qualifyURL = function(pathOrURL) { if (!(new RegExp('^(http(s)?[:]//)','i')).test(pathOrURL)) { return $(document.body).data('base') + pathOrURL; } return pathOrURL; }; //Use this helper function when calling $.ajax $.ajax({ url: qualifyURL(url), ... }); 

This worked great with my phone. Hope this helps.

+14
source

The semantically correct way to do this is to use the <base> :

 <head> <base href="http://mydomain.com/"> </head> 

Then, extract a value similar to this (unfortunately jQuery.ajax () does not get this value automatically):

 $('head base').attr('href'); 

Link to the item: http://www.w3.org/TR/html4/struct/links.html#edef-BASE

+32
source

Both identified answers have serious flaws. Requiring that the function 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 fine most of the time, but it causes some problems if you are doing heavy duty work with SVG. Here's a simple solution that captures all of your URLs at once without using a base tag.

 var baseUrl = 'http://my.hardcoded.url/'; $.ajaxSetup({ beforeSend: function(xhr, options) { options.url = baseUrl + options.url; } }) 
+22
source

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

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

Source: https://habr.com/ru/post/892967/


All Articles