問題描述
如何檢查 jQuery.ajax() 請(qǐng)求頭狀態(tài)是否為304 Not Modified"?
How to check if jQuery.ajax() request header Status is "304 Not Modified"?
jqXHR.status
通常返回 200
,即使請(qǐng)求的標(biāo)頭是304 Not Modified".
jqXHR.status
usually returns 200
, even when requested header is "304 Not Modified".
ifModified:true
沒有太大幫助,因?yàn)樗茐牧?XHR 數(shù)據(jù)請(qǐng)求.
ifModified:true
does not help a lot because it breaks XHR data request.
推薦答案
不手動(dòng)處理緩存頭是不可能的.通常,無法通過 XHR API 獲得 304 響應(yīng):
Without handling cache headers manually, it is not possible. Normally, 304 responses are not made available through the XHR API:
對(duì)于作為用戶代理生成的條件請(qǐng)求的結(jié)果的 304 Not Modified 響應(yīng)用戶代理必須像服務(wù)器給出具有適當(dāng)內(nèi)容的 200 OK 響應(yīng)一樣行事.
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.
jQuery 通常不知道有 304 響應(yīng),因?yàn)闉g覽器會(huì)禮貌地向 JavaScript 撒謊,告訴 JavaScript 網(wǎng)絡(luò)上實(shí)際發(fā)生的事情.
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.
但有一個(gè)好消息(有點(diǎn)):您可以讓 Ajax 產(chǎn)生 304 響應(yīng),但只能通過手動(dòng)設(shè)置 HTTP 緩存頭 If-Modified-Since
或 If-None-Match
在請(qǐng)求中:
But there is good news (kind of): you can get Ajax to produce a 304 response, but only by manually setting the HTTP cache headers If-Modified-Since
or If-None-Match
in the request:
用戶代理必須允許 setRequestHeader()
通過設(shè)置請(qǐng)求標(biāo)頭來覆蓋自動(dòng)緩存驗(yàn)證(例如,If-None-Match
、If-Modified-自
),在這種情況下必須通過 304 Not Modified 響應(yīng).
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.
所以,你可以使用如下代碼:
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();
一個(gè)基本的困難是你怎么知道要發(fā)送的最后修改日期或ETag?em> 瀏覽器具有用于發(fā)送請(qǐng)求的緩存信息,但它不會(huì)與 JavaScript 共享該信息.幸運(yùn)的是,jQuery 會(huì)跟蹤來自 Ajax 響應(yīng)的 Last-Modified
和 ETag
標(biāo)頭,因此您可以使用 ifModified:true
讓 jQuery 設(shè)置這些標(biāo)頭下次發(fā)送對(duì)該資源的請(qǐng)求時(shí)的標(biāo)頭值.
One fundamental difficulty is how do you know what last-modified date or ETag to 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.
有兩點(diǎn)需要注意:
304 響應(yīng)不攜帶數(shù)據(jù).這是設(shè)計(jì)使然.假設(shè)是,如果您選擇使用緩存,您應(yīng)該已經(jīng)在緩存中擁有數(shù)據(jù)的副本!如果沒有從服務(wù)器獲取數(shù)據(jù)是一個(gè)問題(即,因?yàn)槟€沒有該數(shù)據(jù))為什么要使用緩存?當(dāng)您手頭有舊數(shù)據(jù)并且只需要新數(shù)據(jù)時(shí),應(yīng)該使用緩存;因此,使用 304 取回任何數(shù)據(jù)應(yīng)該不是問題.
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 必須存儲(chǔ)上一個(gè)請(qǐng)求的最后修改日期或 ETag(與 If-None-Match
一起使用).流程是這樣的:
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:
第一次獲取:jQuery 沒有緩存信息,所以它不會(huì)發(fā)送
If-Modified-Since
或If-None-Match
.當(dāng)響應(yīng)返回時(shí),服務(wù)器可能會(huì)宣布最后修改的數(shù)據(jù)或 ETag,jQuery 將其存儲(chǔ)以供將來使用.
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.
后續(xù)提取:jQuery 擁有上次提取的緩存信息并將該數(shù)據(jù)轉(zhuǎn)發(fā)到服務(wù)器.如果資源沒有改變,Ajax 請(qǐng)求會(huì)得到 304 響應(yīng).如果資源已更改,Ajax 請(qǐng)求會(huì)收到 200 響應(yīng),以及新的緩存信息供 jQuery 用于下一次獲取.
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 不在頁面重新加載之間保留緩存信息(例如,在 cookie 中).因此,頁面重新加載后第一次獲取資源永遠(yuǎn)不會(huì)是 304,因?yàn)?jQuery 沒有要發(fā)送的緩存信息(即,我們重置回第一次獲取"情況).jQuery 沒有理由不能持久化緩存信息,但目前它沒有.
jQuery does not persist cache information (e.g., in cookies) between page reloads, however. Therefore, the first fetch of a resource after a page reload will never be 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't persist cache information, but at present it doesn't.
這里的底線是您可以使用緩存標(biāo)頭來獲取 JavaScript 304 響應(yīng),但您不能訪問 瀏覽器自己的 ETag 或特定資源的上次修改日期.因此,瀏覽器本身可能知道有關(guān)資源的緩存信息,但您的 JavaScript 代碼不知道.在這種情況下,瀏覽器將使用其緩存標(biāo)頭來獲得真正的 304 響應(yīng),但會(huì)將 200 響應(yīng)轉(zhuǎn)發(fā)到您的 JavaScript 代碼,因?yàn)?JavaScript 沒有發(fā)送任何緩存信息.
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 own ETag 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 請(qǐng)求與實(shí)際的網(wǎng)絡(luò) 304 響應(yīng)完全一致,因?yàn)槟臑g覽器知道的緩存信息和您的 JavaScript 代碼知道的緩存信息可能以不可預(yù)知的方式不同.但是,大多數(shù)情況下正確獲取 304 請(qǐng)求足以滿足大多數(shù)實(shí)際開發(fā)需求.
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.
這是一個(gè)用 Node.js 編寫的簡短服務(wù)器示例(但它應(yīng)該足夠簡單,可以移植到其他語言):
Here's a brief server example written in Node.js (but it should be simple enough to port to other langauges):
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);
運(yùn)行此服務(wù)器時(shí),您可以在瀏覽器中加載頁面并在瀏覽器控制臺(tái)中執(zhí)行兩種不同的測試:
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); }
此腳本將始終看到 200
響應(yīng),即使瀏覽器提供 If-Modified-Since
請(qǐng)求標(biāo)頭并獲得 304
(這將發(fā)生在第一個(gè)請(qǐng)求之后,在瀏覽器看到服務(wù)器的 Last-Modifed
響應(yīng)頭之后).
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).
相比之下,此腳本將總是看到 304 響應(yīng):
By contrast, this script will always see 304 response:
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); }
腳本提供自己的 If-Modified-Since
請(qǐng)求標(biāo)頭(服務(wù)器最后修改日期后兩天);它不依賴于瀏覽器為 If-Modified-Since
提供的任何內(nèi)容,因此允許(根據(jù) XHR 規(guī)范)查看 304 響應(yīng).
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.
最后,這個(gè)腳本總是會(huì)看到一個(gè)200
:
Finally, this script will always see a 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); }
這是因?yàn)槟_本使用了早于服務(wù)器最后修改日期的 If-Modified-Since
,所以服務(wù)器總是發(fā)送 200
.服務(wù)器不會(huì)發(fā)送 304
因?yàn)樗俣蛻舳藳]有最新版本的緩存副本(即,客戶端宣布自 2 月 12 日以來它看到了更改,但是有一個(gè)2 月 13 日的更改,客戶顯然沒有看到).
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).
這篇關(guān)于如何檢查 jQuery.ajax() 請(qǐng)求標(biāo)頭狀態(tài)是否為“304 未修改"?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!