Alexey Zakharov Alexey Zakharov - 1 year ago 106
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download