我想缓存jQuery AJAX响应,这样我就不需要再次进行网络调用了。
以下是我的JS代码:
$(".btn").on("click", function(){
var id = $(this).data("id");
var url = "https://alert-carpenter.glitch.me/api/movies/"+id;
var loadData = memoize(getDataById);
var data = loadData(url);
console.log(data);
// $("#title").html(data.data.title);
});
function getDataById(url,cache){
$.ajax({
method:"GET",
url: url,
success:function (data){
console.log("ajax data", data);
console.log("cache",cache);
cache[url] = data;
}
});
}
function memoize(fn){
var cache = {}
return function(url){
if(cache[url]!=undefined){
console.log("loading from cache");
return cache[url];
}else{
console.log("loading from server");
fn(url,cache)
return cache[url];
}
}
}
AJAX调用正在获得响应,但是它没有更新缓存响应。
我知道如果我将Cache变量设置为全局,那么我可以简单地在jquery ajax成功函数中更新它。但我不想让Cache全局化。
所以我在这里尝试使用闭包。如果有任何错误,请纠正我。
问题是每次响应按下按钮时都要记住该功能。你有
$(".btn").on("click", function(){
//...
var loadData = memoize(getDataById);
... loadData(input) ...
});
function memoize(fn){
var cache = {}
return function(url){
if(cache[url]!=undefined){
console.log("loading from cache");
return cache[url];
}else{
console.log("loading from server");
fn(url,cache)
return cache[url];
}
}
}
因此,当你调用memoize
时,它正在构建一个新的闭包,可以访问一个新的cache
并返回它。尝试在外面创建memoized loadData
:
var loadData = memoize(getDataById);
$(".btn").on("click", function(){
//...
... loadData(input) ...
});
这样,它具有相同的缓存,可以多次调用相同的缓存。
感谢@Phil H的帮助,我使用Promises解决了未定义的错误。
function getDataById(url, cache) {
return new Promise(function(resolve, reject){
$.ajax({
method: "GET",
url: url,
success: function (data) {
console.log("ajax data", data);
console.log("cache", cache);
cache[url] = data;
resolve(data)
},
error:function(err){
reject(err);
}
});
});
}
在服务器调用中
else {
console.log("loading from server");
fn(url, cache).then(function(response){
console.log("response", response);
changeTitle(response);
});