問題描述
我正在 Google Chrome、Safari 和 Firefox 中使用 XMLHttpRequest 加載 JSON 文件.在所有三個瀏覽器中,我都收到了正確顯示 .loaded
屬性的 ProgressEvent
.但是,.lengthComputable
屬性為 false,.total
屬性為零.我檢查了 Content-Length
HTTP 標頭是否正在發送并且是正確的——它是正確的.響應正在被 gzip 編碼,但 Content-length
正確顯示了編碼長度(解壓縮前).
I am loading a JSON file using XMLHttpRequest in Google Chrome, Safari and Firefox. In all three browsers I am receiving ProgressEvent
s which correctly show the .loaded
property. However the .lengthComputable
property is false and the .total
property is zero. I have checked that the Content-Length
HTTP header is being sent and is correct - it is. The response is being gzip-encoded, but the Content-length
correctly shows the encoded length (before decompression).
為什么總長度在我的ProgressEvent
s 中不可用?
Why would the total length not be available in my ProgressEvent
s?
這是標題:
HTTP/1.1 200 OK
ETag: "hKXdZA"
Date: Wed, 20 Jun 2012 20:17:17 GMT
Expires: Wed, 20 Jun 2012 20:17:17 GMT
Cache-Control: private, max-age=3600
X-AppEngine-Estimated-CPM-US-Dollars: $0.000108
X-AppEngine-Resource-Usage: ms=2 cpu_ms=0 api_cpu_ms=0
Content-Type: application/json
Content-Encoding: gzip
Server: Google Frontend
Content-Length: 621606
注意:該文件是通過 Google App Engine 提供的.
Note: the file is being served via Google App Engine.
這里是 JavaScript:
Here is the JavaScript:
var req;
if (window.XMLHttpRequest){
req = new XMLHttpRequest();
if(req.overrideMimeType){
req.overrideMimeType( "text/json" );
}
}else{
req = new ActiveXObject('Microsoft.XMLHTTP');
}
// Listen for progress events
req.addEventListener("progress", function (event) {
console.log(event, event.lengthComputable, event.total);
if (event.lengthComputable) {
self.progress = event.loaded / event.total;
} else if (this.explicitTotal) {
self.progress = Math.min(1, event.loaded / self.explicitTotal);
} else {
self.progress = 0;
}
self.dispatchEvent(Breel.Asset.ON_PROGRESS);
}, false);
req.open('GET', this.url);
注意:該代碼中的 console.log
顯示數百個具有最新 .loaded
的事件,但 .lengthComputable
始終是false 并且 .total
始終為零.self
指的是負責這個 XMLHttpRequest
的對象.
Note: The console.log
in that code is showing hundreds of events with up to date .loaded
s but .lengthComputable
is always false and .total
is always zero. self
refers to the object responsible for this XMLHttpRequest
.
推薦答案
如果 XMLHttpRequestProgressEvent 中的 lengthComputable 為 false,則意味著服務器從未在響應中發送 Content-Length 標頭.
If lengthComputable is false within the XMLHttpRequestProgressEvent, that means the server never sent a Content-Length header in the response.
如果您使用 nginx 作為代理服務器,這可能是罪魁禍首,尤其是如果它沒有將上游服務器的 Content-Length 標頭通過代理服務器傳遞到瀏覽器.
If you're using nginx as a proxy server, this might be the culprit, especially if it's not passing the Content-Length header from the upstream server through the proxy server to the browser.
這篇關于為什么 ProgressEvent.lengthComputable 為假?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!