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