簡體   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