如何检查 jQuery.ajax() 请求头状态是否为“304 Not Modified”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5173656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if jQuery.ajax() request header Status is "304 Not Modified"?
提问by Binyamin
How to check if jQuery.ajax()request header Status is "304 Not Modified"?
如何检查jQuery.ajax()请求头状态是否为“304 Not Modified”?
jqXHR.status
usually returns 200
, even when requested header is "304 Not Modified".
jqXHR.status
通常返回200
,即使请求的标头是“304 Not Modified”。
ifModified:true
does not helpa lot because it breaks XHR data request.
ifModified:true
没有太大帮助,因为它破坏了 XHR 数据请求。
回答by apsillers
Without handling cache headers manually, it is not possible. Normally, 304 responses are not made available through the XHR API:
如果不手动处理缓存头,这是不可能的。通常,无法通过XHR API提供 304 响应:
For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content.
对于由用户代理生成的条件请求导致的 304 Not Modified 响应,用户代理必须像服务器提供具有适当内容的 200 OK 响应一样工作。
jQuery normally doesn't know there was a 304 response, because the browser tells polite lies to JavaScript about what is actually happening over the network.
jQuery 通常不知道有 304 响应,因为浏览器会礼貌地向 JavaScript 撒谎,说明网络上实际发生的事情。
But there is good news (kind of): you canget Ajax to produce a 304 response, but only by manually setting the HTTP cache headersIf-Modified-Since
or If-None-Match
in the request:
但是有个好消息(有点):您可以让 Ajax 产生 304 响应,但只能通过手动设置HTTP 缓存标头If-Modified-Since
或If-None-Match
在请求中:
The user agent must allow
setRequestHeader()
to override automatic cache validation by setting request headers (e.g.,If-None-Match
,If-Modified-Since
), in which case 304 Not Modified responses must be passed through.
用户代理必须允许
setRequestHeader()
通过设置请求标头(例如,If-None-Match
,If-Modified-Since
)来覆盖自动缓存验证,在这种情况下,必须传递 304 Not Modified 响应。
So, you can use code like:
因此,您可以使用以下代码:
var xhr = new XMLHttpRequest();
xhr.open("GET", "foo.html");
xhr.setRequestHeader("If-Modified-Since", "Fri, 15 Feb 2013 13:43:19 GMT");
xhr.send();
One fundamental difficulty is how do you know what last-modified date or ETagto send?The browser has cache information that it uses for sending requests, but it won't share that information with JavaScript. Fortunately, jQuery keeps track of the Last-Modified
and ETag
headers from Ajax responses, so you can use ifModified:true
to have jQuery set those header values the next time it sends a request for that resource.
一个基本的困难是如何知道要发送的最后修改日期或ETag是什么?浏览器具有用于发送请求的缓存信息,但它不会与 JavaScript 共享该信息。幸运的是,jQuery 会跟踪来自 Ajax 响应的Last-Modified
和ETag
标头,因此您可以使用ifModified:true
让 jQuery 在下一次发送对该资源的请求时设置这些标头值。
Two things to note about this:
关于这点需要注意两点:
304 responses do not carry data. This is by design. The assumption is that if you have elected to use caching, you should have a copy of the data already in your cache! If getting no data from the sever is a problem (i.e., because you don't already have that data) why are you using caching? Caching should be used when you have the old data on hand and only want new data; thus, getting back no data with a 304 should not be a problem.
jQuery must have a last-modified date or an ETag (to use with
If-None-Match
) stored from a previous request. The process goes like this:First fetch: jQuery has no cache information, so it doesn't send
If-Modified-Since
orIf-None-Match
. When the response comes back, the server may announce a last-modified data or an ETag, which jQuery stores for future use.Subsequent fetches: jQuery has cache information from the last fetch and forwards that data to the server. If the resource has not changed, the Ajax request gets a 304 response. If the resource has changed, the Ajax request gets a 200 response, along with new cache information for jQuery to use for its next fetch.
jQuery does notpersist cache information (e.g., in cookies) between page reloads, however. Therefore, the first fetch of a resource after a page reload will neverbe a 304, because jQuery has no cache information to send (i.e., we reset back to the "first fetch" case). There is no reason why jQuery couldn'tpersist cache information, but at present it doesn't.
304 响应不携带数据。这是设计使然。假设是,如果您选择使用缓存,那么您的缓存中应该已经有一份数据副本!如果没有从服务器获取数据是个问题(即,因为您还没有这些数据),为什么要使用缓存?当你手头有旧数据而只想要新数据时,应该使用缓存;因此,使用 304 不返回任何数据应该不是问题。
jQuery 必须有一个上次修改的日期或一个 ETag(与 一起使用
If-None-Match
)存储在先前的请求中。这个过程是这样的:第一次获取:jQuery 没有缓存信息,因此它不会发送
If-Modified-Since
或If-None-Match
. 当响应返回时,服务器可能会宣布最后修改的数据或 ETag,jQuery 存储这些数据以备将来使用。后续提取:jQuery 具有上次提取的缓存信息并将该数据转发到服务器。如果资源没有改变,Ajax 请求会得到 304 响应。如果资源已更改,则 Ajax 请求会收到 200 响应,以及新的缓存信息供 jQuery 用于其下一次获取。
然而,jQuery不会在页面重新加载之间保留缓存信息(例如,在 cookie 中)。因此,页面重新加载后对资源的第一次获取永远不会是 304,因为 jQuery 没有要发送的缓存信息(即,我们重置回“第一次获取”的情况)。jQuery 没有理由不能持久化缓存信息,但目前它没有。
The bottom line here is that you can use cache headers to get a JavaScript 304 response, but you can't access the browser's ownETag or last-modified date for a particular resource. So, the browser itself might know caching information about a resource, but your JavaScript code does not. In that case, the browser will use its cache headers to potentially get a real 304 response, but forward a 200 response to your JavaScript code, because JavaScript didn't send any cache information.
这里的底线是,您可以使用缓存标头来获取 JavaScript 304 响应,但您无法访问浏览器自己的ETag 或特定资源的上次修改日期。因此,浏览器本身可能知道有关资源的缓存信息,但您的 JavaScript 代码不知道。在这种情况下,浏览器将使用其缓存标头潜在地获得真正的 304 响应,但将 200 响应转发给您的 JavaScript 代码,因为 JavaScript 没有发送任何缓存信息。
It is not possible to make JavaScript 304 requests align perfectly with actual network 304 responses, because the cache information known by your browser and the cache information known by your JavaScript code may differ in unpredictable ways. However, getting 304 requests correctly most of the time is good enough for most practical development needs.
使 JavaScript 304 请求与实际网络 304 响应完全一致是不可能的,因为浏览器已知的缓存信息和 JavaScript 代码已知的缓存信息可能以不可预测的方式不同。但是,在大多数情况下正确获取 304 请求足以满足大多数实际开发需求。
Example
例子
Here's a brief server example written in Node.js (but it should be simple enough to port to other langauges):
这是一个用 Node.js 编写的简短服务器示例(但它应该足够简单以移植到其他语言):
require("http").createServer(function (req, res) {
console.log(req.headers["if-modified-since"]);
// always send Last-Modifed header
var lastModDate = "Fri, 13 Feb 2013 13:43:19 GMT";
res.setHeader("Last-Modified", lastModDate);
// if the request has a If-Modified-Since header,
// and it's newer than the last modification,
// then send a 304 response; otherwise send 200
if(req.headers["if-modified-since"] &&
Date.parse(lastModDate) <= Date.parse(req.headers["if-modified-since"])) {
console.log("304 -- browser has it cached");
res.writeHead(304, {'Content-Type': 'text/plain'});
res.end();
} else {
console.log("200 -- browser needs it fresh");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('some content');
}
}).listen(8080);
When running this server, you can load the page in your browser and perform two different tests in your browser console:
运行此服务器时,您可以在浏览器中加载页面并在浏览器控制台中执行两种不同的测试:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/");
xhr.send();
xhr.onload = function() { console.log(xhr.status); }
This script will always see a 200
response, even if the browser supplies a If-Modified-Since
request header and gets a 304
(which will happen all requests after the first, after the browser sees the server's Last-Modifed
response header).
该脚本将始终看到200
响应,即使浏览器提供了If-Modified-Since
请求标头并获得了一个304
(在第一个之后的所有请求都会发生,在浏览器看到服务器的Last-Modifed
响应标头之后)。
By contrast, this script will alwayssee 304 response:
相比之下,这个脚本总是会看到 304 响应:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/");
xhr.setRequestHeader("If-Modified-Since", "Fri, 15 Feb 2013 13:43:19 GMT");
xhr.send();
xhr.onload = function() { console.log(xhr.status); }
The script supplies its own If-Modified-Since
request header (two days after the server's last-modified date); it does not rely on whatever the browser supplies for If-Modified-Since
, and therefore is allowed (per the XHR spec) to see 304 responses.
脚本提供自己的If-Modified-Since
请求头(服务器上次修改日期后两天);它不依赖于浏览器为 提供的任何内容If-Modified-Since
,因此允许(根据 XHR 规范)查看 304 响应。
Finally, this script will always see a 200
:
最后,此脚本将始终看到200
:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/");
xhr.setRequestHeader("If-Modified-Since", "Fri, 12 Feb 2013 13:43:19 GMT");
xhr.send();
xhr.onload = function() { console.log(xhr.status); }
This is because the script uses a If-Modified-Since
that is prior to the server's last-modified date, so the server always sends a 200
. The server won't send a 304
because it assumes the client doesn't have a cached copy of the most recent version (i.e., the client announces that it's seen changes since Feb 12, but there was a change on Feb 13 that the client apparently hasn't seen).
这是因为脚本使用了If-Modified-Since
在服务器上次修改日期之前的 ,所以服务器总是发送200
. 服务器不会发送 ,304
因为它假定客户端没有最新版本的缓存副本(即,客户端宣布自 2 月 12 日以来它已经看到了更改,但 2 月 13 日发生了更改,客户端显然没看过)。
回答by B.F.
Also the headers will be cached if the response comes from cache. I took this as a chance. My server sends a unique md5 header. This has not the same effect like ?query=time(). Now on JS side verify the lastest md5 header with the current. If you receive the same MD5 header as before the response is coming from cache. I forgot all about JQuery but saw it's possible to set and read headers.
如果响应来自缓存,则标头也将被缓存。我把这当作一个机会。我的服务器发送一个唯一的 md5 标头。这与 ?query=time() 的效果不同。现在在 JS 端用当前验证最新的 md5 标头。如果您收到与之前相同的 MD5 标头,则响应来自缓存。我忘记了 JQuery,但看到可以设置和读取标头。
<?php
$oldMD5=filter_input(INPUT_SERVER,'HTTP_CONTENT_MD5',int);
if(!empty($oldMD5)){
header('Content-MD5: '.(1+(int)$oldMD5));
}
--------------------------------------------------------------
<script>
var oldMD5=0;
//your Ajax implementation
Ajax.setRequestHeader('Content-MD5',''+oldMD5);
var newMD5=parseInt(Ajax.getResponseHeader('Content-MD5'),10);
if(newMD5 && oldMD5<newMD5,10){
oldMD5=newMD5;
//not cached
}else{
//cached
}
This is a little bit abuse, because md5 should be a hash for to verify that the 'decoded data are the same data that were initially sent'.
这有点滥用,因为 md5 应该是一个哈希值,用于验证“解码数据与最初发送的数据相同”。
回答by Binyamin
I have kind of implementation in https://github.com/laukstein/ajax-seo/blob/cbed03222d89f6f7e75dc49ce8882c30201bbb86/index.php#L266-274
我在https://github.com/laukstein/ajax-seo/blob/cbed03222d89f6f7e75dc49ce8882c30201bbb86/index.php#L266-274 中有一种实现
var cache;
$.ajax({
...
beforeSend: function() {
cache = setTimeout(function() {
console.log('The content not cached jet.');
}, 300);
},
success: function(data) {
if (cache) {
clearTimeout(cache);
}
}
});
回答by dmackerman
Maybe try this?
也许试试这个?
$.ajax({
url: 'your-url',
dataType: 'script',
complete: function(xhr) {
if (xhr.status == 304) return;
// or better: if (xhr.status != 200) return;
// your code goes here
}
});
回答by Nic Meiring
open your browsers inspector and it will show you info on the ajax request, including the status.
打开浏览器检查器,它会显示有关 ajax 请求的信息,包括状态。
for chrome, right click and choose inspect element, then go to the Network tab.
对于 chrome,右键单击并选择检查元素,然后转到网络选项卡。
for firefox, just use firebug and follow the same steps.
对于 firefox,只需使用 firebug 并按照相同的步骤操作即可。