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

Posted by Mr. Bombastic on Stack Overflow See other posts from Stack Overflow or by Mr. Bombastic
Published on 2012-12-13T04:34:58Z Indexed on 2012/12/13 5:03 UTC
Read the original article Hit count: 167

Filed under:
|
|
|
|

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!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery