1

This is similar to this question Make jquery jqxhr act like already sending request but that doesn't seem to solve my problem.

I'm using a framework where there are lots of requests done using jQuery ajax methods, and I have to hook in the middle of that (but without touching the original code) to emulate some responses from the server.

With ajaxSend I can detect whenever a request is being send, so at that point I know which ones I want to stop and provide my precomputed response, but I can't find a way to do it. One possible deep level alternative would be to ignore jQuery and go for a Service Worker, but that would restrict the browsers where this will work and it can mean also added complexity to the logic about the precomputed responses, so I would like to stay with a jQuery solution.

For starters I would be happy to have a first step just by being able to stop the request from touching the network, but although I tried to stop the event, the xhr is always executed.

    $( document ).ajaxSend(function(event, request, settings) {
        console.log(request)
        event.preventDefault()
        event.stopPropagation()
        return false;
    }

Then the next step (or may it's this one) is using the request object to resolve the promise, but it doesn't have a 'resolve' method, so I guess that it's a restricted Promise

Can anyone help me to find a solution?

Community
  • 1
  • 1
AlfonsoML
  • 12,634
  • 2
  • 46
  • 53

1 Answers1

0

I did something similar to this a while back by overriding $.ajax.

(function ($) {
    var jqAjax = $.ajax;
    $.ajax = function (settings) {
        if(someCriteriaToDetermineIfItsLocalOrNot) {
           // get from local storage, and return a promise or something
        } else
            return jqAjax(settings);
    };
} (jQuery));
David784
  • 7,031
  • 2
  • 22
  • 29