How to cheat jqXHR to succeed always

I try to make jQuery ajax calls always return as if they succeeded, for example even if I don't have a network, I will return some locally stored data

Is it possible?

I tried using $ .ajaxPrefilter and called the jqXHR success function, but it still won’t behave as if the request completed: (

Thanks!

+3
source share
4 answers

Well, quick update: not one of the above solutions.
What I eventually had to do to get around this problem is to replace the jQuery ajax function with my implementation, which checks for network connectivity.
if there is, I proxy the request back to the original ajax function, otherwise I create the same return structure as ajax and return it

Again, I hate answering my questions, especially when this is not an answer, but rather a workaround. sad ...

-1
source

If I understand you correctly, do you want to make the jqXHR action the way it happened when it really didn't work?

If so, .pipe is your friend :)

var jqDeferred = $.ajax(...something something); //make the deferred always resolve as success, calling all success callbacks on original. //AFAIK, dosent pass any arguments to the original success callbacks. jqDeferred.pipe( null, function(args){ return $.Deferred().resolve(); }); //same as above, but try to pass all arguments through to the success callbacks. jqDeferred.pipe( null, function(args){ return $.Deferred().resolve.apply(this, arguments); }); 

I wanted to do this recently and could not find any simple instructions, hope this helps. I'm not sure about passing the argument, because I used only the first form in anger - we don't need the arguments passed to our success callbacks.

The pipe is evil.

+3
source

I think you should handle this ajax error with any code for your needs.

error (jqXHR, textStatus, errorThrown)

Function A function that should be if the request fails. The function receives three arguments: jqXHR (in jQuery 1.4.x, XMLHttpRequest), a string describing the type of error that occurred and the optional exception of the object if it occurred. Possible values ​​for the second argument (other than zero) are timeout, error, abort, and parsererror. When an HTTP Error occurs, errorThrown receives the text part of the HTTP Status, for example, "Not Found" or "Internal Server Error." Starting with jQuery 1.5, the error parameter can take many functions. Each function will be called in turn. Note. This handler is not called for cross-domain script and JSONP. This is an Ajax Event.

Example

  error: function (xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); if (err.Message == 'SomeMessage') { //Return Your data, handle this error... } } 
0
source

You can use .ajaxSetup with your own beforeSend handler. In your handler, you can check if the url is accessible if you cannot cancel the request and emulate a success call with your own data.

0
source

Source: https://habr.com/ru/post/889915/


All Articles