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

发布于 2024-11-27 02:50:09 字数 911 浏览 0 评论 0原文

我试图为我的 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);
});

这不能按预期工作。有时确实如此,但代码中存在范围问题。有什么办法可以真正伪造整个请求吗?以便回调机制继续下去。类似于

请求 => Hook Ajax 调用(停止调用,设置响应)==>继续阿贾克斯

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回首观望 2024-12-04 02:50:09

另一种选择是覆盖 $.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));

Another option is to override the $.ajax method. You can try out my fiddle. Internally the $.ajax method is used for load, get, and post.

(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));
握住我的手 2024-12-04 02:50:09

也许我错了,但如果我点击缓存,我什至不会启动 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);
     });
});

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.

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);
     });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文