如何修复浏览器缓存和未修改的 JSON 响应? jQuery.ajax({ifModified:true,cache:true}) JSON 请求在数据响应时中断

发布于 2024-10-19 03:21:25 字数 1013 浏览 1 评论 0原文

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

第一次浏览器请求 http://localhost/api 返回状态 200 OK 并下一步 304 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第一次返回ok:

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

但下次返回data undefined

304:notmodified
undefined

如何解决?看来是 jQuery 1.5.1 的 bug。 预期结果:

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

How to fix browser cache and notmodified respond for JSON? jQuery.ajax({ifModified:true,cache:true}) JSON request break on data respond.

First time browser request http://localhost/api returns status 200 OK and nexts 304 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 first time returns ok:

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

but on next times returns data undefined:

304:notmodified
undefined

How to solve it? It seems jQuery 1.5.1 bug. Expected result:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

因为看清所以看轻 2024-10-26 03:21:25

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

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

我不确定 HTTPS 如何与 etag 一起使用,但是,HTTPs 数据并不总是被缓存(浏览器和版本之间的方法和行为不同),因此如果 etag 工作,您可能无论如何都需要实现自己的安全缓存。

I believe this is how it is supposed to work a 304 doesn't return any data it just tells you it hasn't changed.

However, I do see the problem if you haven't got the data already in memory then you need some method to get it from the browsers cache. Therefore I think the solution is the write code to cache the data.

I am not sure how HTTPS works with etags, however, HTTPs data isn't always cached (different methods and behaviour between browsers and versions) so if etags work you may need to implement your own secure cache anyway.

伪装你 2024-10-26 03:21:25

尝试在 url 末尾添加一个随机数作为参数。

random_number = Math.floor(Math.random()*10101010101)
url:'http://localhost/api?' + random_number

Try adding a random number to the end of your url as a param.

random_number = Math.floor(Math.random()*10101010101)
url:'http://localhost/api?' + random_number
孤独患者 2024-10-26 03:21:25

当您收到 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);
    }
});

When you receive a 304 you must re-request the data but with the "ifModified" flag set to false. The request will then be subject to normal caching rules and you will receive your cached data.

For instance, in an MVC controller...

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

The data sent back is cached on the client for up to 1 day.

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);
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文