Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.getJSON: how to avoid requesting the json-file on every refresh? (caching)

in this example you can see a generated HTML-list. On every refresh the script requests the data-file (ajax/test.json) and builds the list again.

The generated file "ajax/test.json" is cached statically. But how can I avoid requesting this file on every refresh?

// source: jquery.com
$.getJSON('ajax/test.json', function(data) {
    var items = [];

    $.each(data, function(key, val) {
        items.push('<li id="' + key + '">' + val + '</li>');
    });

    $('<ul/>', {
        'class': 'my-new-list',
        html: items.
    }).appendTo('body');
});

This doesn't work:

list_data = $.cookie("list_data");
if (list_data == undefined || list_data == "") {
    $.getJSON('ajax/test.json', function(data) {
        list_data = data;
    });
}

var items = [];
$.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
});

$('<ul/>', {
    'class': 'my-new-list',
    html: items.
}).appendTo('body');

Thanks in advance!

like image 406
Mr. B. Avatar asked Dec 21 '22 12:12

Mr. B.


2 Answers

How 'bout a promise ?

var list_data = localStorage.getItem("list_data"),
          def = $.Deferred();

if (!list_data) {
    def = $.getJSON('ajax/test.json', function(data) {
        list_data = data;
        localStorage.setItem("list_data", JSON.stringify(list_data));
    });
}else{
    list_data = JSON.parse(list_data);
    def.resolve();
}

def.done(function() {
    var items = [];
    $.each(list_data, function(key, val) {
        items.push( $('<li />', {id: key, text: val}) );
    });

    $('<ul/>', {'class': 'my-new-list'}).html(items).appendTo('body');
});
​

I'd also just use local storage, and if IE7 or below is to be supported, use the shim available on MDN!

like image 64
adeneo Avatar answered Jan 11 '23 23:01

adeneo


Because your code loops through data which is not in the scope where your $.each is. Instead:

list_data = $.cookie("list_data");

function buildList(data) {
    var items = [];

    $.each(data, function(key, val) {
        items.push('<li id="' + key + '">' + val + '</li>');
    });

    $('<ul/>', {
        'class': 'my-new-list',
        html: items.
    }).appendTo('body');
}

//if we dont have list data
if (!list_data) {
    //request for the data
    $.getJSON('ajax/test.json', function(data) {
        list_data = data;
        //build list using new data
        buildList(data);
    });
} else {
    //or use existing list data
    buildList(list_data)
}
like image 30
Joseph Avatar answered Jan 11 '23 23:01

Joseph