3

如何修复浏览器缓存并notmodified响应 JSON?jQuery.ajax({ifModified:true,cache:true})JSON 请求在data响应时中断。

第一次浏览器请求http://localhost/api返回状态200 OK和nexts304 Not Modified

$.ajax({
    type:"GET",
    url:'http://localhost/api', // {"content"="Hello!"}
    dataType:'json',
    cache:true,
    ifModified:true,            // Lets respond `304:notmodified`
    success:function(data,textStatus,jqXHR){
        console.debug(jqXHR.status+':'+textStatus);
        console.debug(data);    // Why on repeated request returns `undefined`?
    }
});

XHR 第一次返回正常:

200:success
Object {content="Hello!"}

但在下一次返回data undefined

304:notmodified
undefined

如何解决?似乎是 jQuery 1.5.1 的错误。预期结果:

304:notmodified
Object {content="Hello!"}
4

3 回答 3

1

我相信这就是它应该如何工作的 304 不返回任何数据,它只是告诉你它没有改变。

但是,如果您还没有在内存中获取数据,我确实看到了问题,那么您需要一些方法从浏览器缓存中获取它。因此我认为解决方案是编写代码来缓存数据。

我不确定 HTTPS 如何与 etags 一起工作,但是,HTTPS 数据并不总是被缓存(浏览器和版本之间的方法和行为不同),所以如果 etags 工作,你可能需要实现自己的安全缓存。

于 2011-08-01T09:50:43.847 回答
-1

当您收到 304 时,您必须重新请求数据,但将“ifModified”标志设置为 false。然后,该请求将受到正常缓存规则的约束,您将收到您的缓存数据。

例如,在 MVC 控制器中......

        DateTime pageLastUpdated = <.....>

        if (Request.Headers["If-Modified-Since"] != null)
        {
            var dt = DateTime.Parse(Request.Headers["If-Modified-Since"] as string);

            if (pageLastUpdated.Date == dt.Date && pageLastUpdated.Hour == dt.Hour && pageLastUpdated.Minute == dt.Minute && pageLastUpdated.Second == dt.Second) {
              Response.Cache.SetCacheability(HttpCacheability.NoCache);                    
              return new HttpStatusCodeResult(304, "notmodified");
            }
        }

        Response.Cache.SetCacheability(HttpCacheability.Private);
        Response.Cache.SetVaryByCustom("*");
        Response.Cache.SetExpires(pageLastUpdated.AddDays(1));
        Response.Cache.SetLastModified(pageLastUpdated);

        // now return the Json
        return Json(new {........});

发回的数据在客户端缓存最多 1 天。

function loadJson(url, params, onLoaded) {
  // initial request 
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    data: params,
    cache: true,
    ifModified: true, // forces check with server
    success: function (result, textStatus, jqXHR) {

        // if 304, re-request the data
        if (result === undefined && textStatus == 'notmodified') {
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: url,
                data: params,
                cache: true,
                ifModified: false, // don't check with server
                success: function (cachedResult, textStatus, jqXHR) {
                    onLoaded(cachedResult);
                }
            });
        }
        else
            onLoaded(result);
    }
});
于 2012-09-29T13:29:27.400 回答
-1

尝试在您的网址末尾添加一个随机数作为参数。

random_number = Math.floor(Math.random()*10101010101)
url:'http://localhost/api?' + random_number
于 2011-03-31T20:38:07.553 回答