繁体   English   中英

如何记住 jquery ajax 响应?

[英]How to memoize jquery ajax response?

我想缓存 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 成功函数中更新它。 但我不想让缓存成为全球性的。

所以在这里我尝试使用闭包。 如果有任何错误,请纠正我。

问题是每次响应按钮按下时,您都在记住该功能。 你有

$(".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并返回的新闭包。 尝试在外部创建记忆化的loadData

var loadData = memoize(getDataById);

$(".btn").on("click", function(){
    //...
    ... loadData(input) ...
});

这样,它是具有相同缓存的同一个闭包,它被多次调用。

感谢@Phil H 的帮助,我已经使用 Promises 解决了 undefin 错误。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM