如何使用 jQuery 读取缓存的 json 数据?

How to read cached json data with jQuery?

使用 jQuery 1 或 2 的最新版本,我有这个发出请求并显示结果的简单代码:

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
        });
    });
});

在第一个请求中,我读取了我的 Json 数据。在第二个请求中,我得到了预期的 304 响应,并且数据未定义。

如何显示浏览器缓存中的数据?

ifModified

的文档

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

我猜已经说明了一切。不要用它,它不是你想的那样。

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

不要试图从客户端引导缓存。那是服务器的任务。设置适当的缓存 headers 客户端将自行运行。