如何在 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);
});
这不能按预期工作。有时确实如此,但代码中存在范围问题。有什么办法可以真正伪造整个请求吗?以便回调机制继续下去。类似于
请求 => 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种选择是覆盖
$.ajax
方法。您可以尝试我的小提琴。在内部,$.ajax
方法用于load
、get
和post
。Another option is to override the
$.ajax
method. You can try out my fiddle. Internally the$.ajax
method is used forload
,get
, andpost
.也许我错了,但如果我点击缓存,我什至不会启动 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.