繁体   English   中英

jQuery延迟了Ajax缓存

[英]jQuery deferred ajax cache

我读了上面的回答这个问题,关于使用jQuery的递延

我正在遍历一组ID。 对于每个ID,我需要从ajax请求中获取有关它的数据,或者如果ajax请求之前已经成功返回了数据,则从缓存中获取有关它的数据。

在每个循环中,我使用$ .when()来观察getData()是在处理该ID之前从缓存还是成功的ajax调用返回了某些内容。 当前的问题是,ID处理仍在继续进行,而没有等待getData()的ajax成功执行。

一些伪代码:

var IDs = ["1", "2", "1", "3", "1"]; 
//ID "1" is repeated
//data for "1" should should require ajax get the first time
//subsequent processing should get data for "1" from dataCache

var dataCache = [];

function getData(ID){
    if (/*data for ID in dataCache*/){
        //return data pertaining to ID from dataCache
    } else {
        return $.getJSON("returnJSONDataByID/" + ID, function(resp){
            //push resp data to dataCache
        })
    }
}

for (/*each item i in IDs*/){
    $.when(getData(IDs[i])).then(function(){
        //process IDs[i] data

        //this is the resolved handler, which should be executed
        //when either getData() returns data from the dataCache,
        //or $.getJSON succeeds
        //PROBLEM: this is currently executing every loop and
        //and doesn't wait for the ajax to return resp
    })
}

问题是您的循环将立即触发所有getData调用,但是结果仅在JSON调用返回后才存储在缓存中。 因此,对于循环中的每个调用,缓存仍然为空,并且每个调用都会执行一个新的JSON请求。

解决方案:将Deferred对象而不是结果存储在缓存中。

var IDs = ["1", "2", "1", "3", "1"];

var dataCache = {};

function getData(id) {
    if (id in dataCache) {
        console.log("Cache hit for ID " + id);
        return dataCache[id];
    } else {
        console.log("Retrieving data for ID " + id);
        var deferred = $.getJSON("http://jsfiddle.net/echo/jsonp/?callback=?", {
            id: id
        }, function(response) {
            console.log("Retrieved data for ID " + id);
        });
        dataCache[id] = deferred;
        return deferred;
    }
}

for (var i=0; i<IDs.length; i++) {
    $.when(getData(IDs[i])).then(function(result) {
        console.log("result: " + result.id);
    });
}

注意:这是有效的代码,您可以在jsFiddle中使用它

暂无
暂无

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

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