如何在JQuery中使用localStorage为Ajax调用创建自定义缓存机制? [英] How to create custom cache mechanism for ajax calls using localStorage in JQuery?

查看:212
本文介绍了如何在JQuery中使用localStorage为Ajax调用创建自定义缓存机制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

但是我不知道如何伪造JQuery.ajax的请求完成.我可以成功拦截该调用,但是由于某种原因,我对回调函数的调用没有相同的作用域.

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

请求=>挂接Ajax呼叫(停止呼叫,设置响应)=>继续ajax

Request => Hook Ajax call (stop call, set response) => Continue ajax

推荐答案

也许我错了,但是如果我命中了缓存,我什至不会启动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.

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

这篇关于如何在JQuery中使用localStorage为Ajax调用创建自定义缓存机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆