2

Background: I'm making a caching mechanism for (json response only) jQuery ajax calls. Upon a successful ajax call I store some data in localstorage: the key which is an identifier specific to the request (I concatenate the method and the url), and the value is the JSON response, along with some metadata like how long until expiration. Upon a second ajax call to the same url with the same method, I check to see if the item exists in localstorage.

Problem: If there a valid entry in localstorage, I want to stop the ajax request to the server, and then trigger a successful ajax response- and inject my localstorage data as the responseJSON.

I see jquery uses the status code to determine a successful ajax response:

// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;

And then later on resolves the deferred:

// Success/Error
if ( isSuccess ) {
    deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
    deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}

Is there a way I can access the jQuery deferred from the $.ajaxPrefilter() method (which is the hook I'm using to do my logic)? If I can access the deferred object I think I could resolve it on my own and then cancel the ajax request with jqXHR.abort() ?

Here is my code: https://gist.github.com/jaredrada/7185419

jaredrada
  • 1,130
  • 3
  • 12
  • 25
  • 1
    See similar question [here](http://stackoverflow.com/questions/17639408/how-to-convert-callback-sample-to-deferred-object/17640142). The difference is your desire to use localstorage. You will need to adapt the selected answer. Don't try to use the other answer (by me) - it won't work with localstorage because Promises can't (as far as I'm aware) be reliably stringified (localstorage only stores strings or stringified data). – Beetroot-Beetroot Nov 03 '13 at 11:18
  • @Beetroot-Beetroot I like that solution, which essentially wraps the jquery ajax function and returns the deferred obj (whether from an ajax call or from cached data). I was taking a different approach, modifying the ajax mechanism itself. Thanks for the help. – jaredrada Nov 03 '13 at 14:32

0 Answers0