如何在JQuery中使用localStorage为ajax调用创建自定义缓存机制?

我试图为我的ajax调用编写自定义缓存机制,这些调用主要是数据调用。 因此,我不是将它们放在浏览器缓存中,而是将它们放在localStorage中以供长期使用。

但我无法弄清楚如何伪造JQuery.ajax的请求完成。 我可以成功拦截调用,但由于某种原因,我对回调函数的调用没有相同的范围。

$.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); }); 

这不按预期工作。 它有时会,但代码中存在范围问题。 我有什么方法可以伪造整个请求吗? 这样回调机制就像它一样继续。 就像是

Request => Hook Ajax调用(停止调用,设置响应)=>继续ajax

也许我错了,但如果我点击缓存,我甚至不会开始ajax调用。 这就是我通常使用缓存的方式,我认为你可以调整它来使用本地存储而不是缓存对象。

 var cache = {}; var complete = function(data) {}; $("input").change(function(){ var val = this.value; // key exists in cache-object, use it! if (cache[val]) return complete(cache[val]); // key doesn't exist yet, get the data an store it in cache. $.get(url, function(response){ cache[val] = response; complete(response); }); }); 

另一种选择是覆盖$.ajax方法。 你可以尝试我的小提琴 。 在内部, $.ajax方法用于loadgetpost

 (function($){ // Store a reference to the original ajax method. var originalAjaxMethod = $.ajax; // Define overriding method. $.ajax = function(options){ var key = ''; if(options.url) key += options.url; if(options.data) key += '?' + options.data; // has made this request if(!!window.localStorage && (key in localStorage)) { // todo: determine which callbacks to invoke var cb = options.complete || options.success; cb.call(this, localStorage[key]); } else { // has not made this request // todo: determine which callbacks to intercept var cb = options.success; options.success = function(responseText){ localStorage[key] = responseText; cb.apply(this, arguments); }; originalAjaxMethod.call( this, options ); } }; }(jQuery));