Search code examples
ajaxjquerycordova

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.


Solution

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

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

    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 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 for my experience with Phonegap. Hopefully this helps.