skip to Main Content

I have an issue with $.ajax when my website has a path base where the url that I specify in javascript is missing the path base and the route is not found. Is there a good strategy for accounting for path base with $.ajax?

I had the idea to use ajaxSetup with beforeSend to alter the url with a prefix, which would allow me to set the url prefix from a global location, instead of having to modify every url string in my code base with the prefix, but if I use beforeSend with my $.ajax call, then the beforeSend established with ajaxSetup is ignored, so I don’t see how that option could be used.

2

Answers


  1. Chosen as BEST ANSWER

    This is what I ended up with. I found that ajaxSend let me do what I couldn't with ajaxSetup. Please, excuse the ASP.Net references.

    <script>
        $(document)
            .ajaxSend(function (event, jqxhr, settings) {
    
                var baseUrl = '@Url.Content("~/")';
                if (!settings.url.startsWith(baseUrl))
                {
                    // need to account for instances where your website has a path base
                    settings.url = baseUrl + settings.url;
                }
    
            })
    </script>
    

  2. Monkey-patch it, run this code once, early on in your application, before any ajax requests (replace http://localhost:4000 with the prefix of your choice):

    (() => {
      let org = $.ajax;
      let prefix = 'http://localhost:4000';
      $.ajax = function (...args) {
        args[0] = prefix + args[0];
        return org.apply(this, args);
      }
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search