Alexey Zakharov Alexey Zakharov - 17 days ago 7
Ajax Question

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

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.


When I dealt with this issue, I just put that information as a data-element on the tag.

 <body data-base=""> ...

And then used that in building out the proper URL for a given request:

 //If pathOrURL is a relative path (e.g. /users/1), then we return a qualified
 // URL, such as
 // 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
   url: qualifyURL(url), ... });

This worked great for my experience with Phonegap. Hopefully this helps.