I was trying to write a custom caching mechanism for my ajax calls, which are mostly just data calls. So instead of putting them in the browser cache, I'm putting them down in localStorage for long term use.
But I cannot figure out how to fake request completion for JQuery.ajax. I can successfully intercept the call but my calls to the callback function do not have the same scope for some reason.
$.ajaxPrefilter(
function( options, originalOptions, jqXHR ) {
var key;
originalOptions.data = originalOptions.data || {};
key = options.localStorageKey = options.url + '?' + $.param(originalOptions.data);
var value = localStorage.getItem(key);
if(value)
{
//Still not working
jqXHR.abort();//Abort this call
options.success(JSON.parse(value));//Call the callback function
return jqXHR();//return xhr for chaining (?)
}
});
$('#logo').ajaxComplete(function(e,xhr,settings) {
//cache the request
localStorage.setItem(settings.localStorageKey,xhr.responseText);
});
This does not work as intended. It does, sometimes, but there are scoping issues in the code. Is there any way I could actually fake the entire request ? So that the callback mechanism continues as it does. Something like
Request => Hook Ajax call (stop call, set response) => Continue ajax
Maybe i'm wrong, but if i hit the cache i don't even start an ajax call. this is how i usually use cache, i think you can adapt it to use local storage instead of a cache object.
Another option is to override the
$.ajax
method. You can try out my fiddle. Internally the$.ajax
method is used forload
,get
, andpost
.