2016-07-12 23 views
0

我已經在Cordova中構建了一個應用程序,它最初將用於IOS,但最終需要在Android和桌面上工作。在線時我需要請求JSON文件並緩存JSON以便在脫機時使用。我正在使用Cordova並使在線/離線事件偵聽器正常工作。應用程序開發 - 在線時緩存JSON文件 - AJAX

這似乎與下面的簡單代碼工作:

var cache = JSON.parse(localStorage.getItem('cache')); 

    if (!cache) $.getJSON('http://example.com/JSON/', function (data) { 
     cache= localStorage.setItem('cache', JSON.stringify(data)); 

    }); 

然而,應用程序是不是比多了幾分複雜,使得動態AJAX調用和我奮力知道如何處理動態URL的高速緩存,其根據類別顯示不同的數據。經過對動態變量的一些研究後,我想出了下面的代碼,但是這不起作用,因爲同一個緩存文件用於App中的所有類別,並且當我將「cache」var打印到控制檯時,我得到NULL。

var cat = (this.getAttribute('data-cat')); 

       //get cached JSON 
       var cache = {}; 
       cache['category-' + cat] = JSON.parse(localStorage.getItem(cache['category-' + cat]));  

       //check if online and not cached - could make this more complex and only do the Ajax call daily 
       if((online===true)&&(!cache['category-' + cat])){ 
        //get JSON 
        $.getJSON(baseurl+'/wp-json/app/v2/files?filter[category]='+cat+'&per_page=100', function(jd) { 
        //cache JSON 
        var cache = {}; 
        cache['category-' + cat] = localStorage.setItem(cache['category-' + cat], JSON.stringify(jd)); 
        cache.date = currentTimestamp; 
        }); 
       } else if((online===false)&&(!cache['category-' + cat])){ 
        alert('There are no cached files. You need to be online.'); 
       } 
console.log(JSON.parse(localStorage.getItem('cache'))); 

任何人都可以看到我做錯了什麼?

回答

1

相反的:

localStorage.getItem(cache['category-' + cat]); 
localStorage.setItem(cache['category-' + cat], JSON.stringify(jd)); 

嘗試:

localStorage.getItem('category-' + cat); 
localStorage.setItem('category-' + cat, JSON.stringify(jd)); 

編輯:

我修改您的代碼,在這裏我的瀏覽器進行測試,我認爲這是你需要什麼:

//var cat = (this.getAttribute('data-cat')); 
var cat = 'myCat'; 
var online = true; 
//get cached JSON 
var cache = {}; 
cache['category-' + cat] = JSON.parse(localStorage.getItem('category-' + cat)); 

//check if online and not cached - could make this more complex and only do the Ajax call daily 
if ((online === true) && (!cache['category-' + cat])) { 
    //get JSON 
    //$.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]=' + cat + '&per_page=100', function (jd) { 
    //mock the 'jd' result from ajax 
    var jd = { 
    prop1: "value1", 
    prop2: "value2" 
    }; 
    //cache JSON 
    //var cache = {}; 
    cache['category-' + cat] = jd 
    localStorage.setItem('category-' + cat, JSON.stringify(jd)); 
    //cache.date = currentTimestamp; 
    cache.date = new Date(); 
    //}); 
} else if ((online === false) && (!cache['category-' + cat])) { 
    alert('There are no cached files. You need to be online.'); 
} 
console.log(JSON.parse(localStorage.getItem('category-' + cat))); 

注意:Ajax是異步的,所以最後的console.log可能無法捕捉到您要查找的內容。

+0

是的工作 - 非常感謝你! – LeeTee

相關問題