Nicolas Zozol
Nicolas Zozol

Reputation: 7048

How to read cached json data with jQuery?

Using last versions of jQuery 1 or 2, I have this simple code that makes a request and shows the result :

var url1 = "cache/1";

var callback1 = function(data, statusText, response){
    $("#result1").html("status :"+response.status);
    $("#result1").append("<p>"+JSON.stringify(data)+"</p>");
};

$(function() {

    $("#query1").on ("click", function(){
        $.ajax({
            url: url1,
            cache: true,
            dataType: 'json',
            ifModified: true,
            success:callback1
        });
    });
});

On the first request, I read my Json data. On the second request, I have a 304 response as expected, and data is undefined.

How can I show data from the browser cache ?

Upvotes: 0

Views: 114

Answers (1)

Tomalak
Tomalak

Reputation: 338396

The documentation of ifModified

ifModified (default: false)
Type: Boolean
Allow the request to be successful only if the response has changed since the last request.

Says it all, I guess. Don't use it, it does not do what you think.

$(function() {
    $("#query1").on("click", function(){
        $.get("cache/1").done(function (data, statusText, response) {
            $("#result1")
                .html("status :"+response.status);
                .append("<p>"+JSON.stringify(data)+"</p>");
        });
    });
});

Don't try to steer caching from the client. That's the server's task. Set proper caching headers and the client will work on its own.

Upvotes: 1

Related Questions