AJAX和FETCH请求进度条
要实现一个AJAX和FETCH请求的进度条,你可以在发送请求前设置一个监听器来跟踪加载的进度。以下是使用AJAX和FETCH分别实现进度条的简单示例。
AJAX 示例:
function updateProgress(event) {
if (event.lengthComputable) {
var percentComplete = (event.loaded / event.total) * 100;
console.log(percentComplete.toFixed(2) + '%');
// 更新进度条的逻辑
}
}
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your-file-url', true);
xhr.onprogress = updateProgress;
xhr.send();
FETCH 示例:
fetch('your-file-url', {
method: 'GET',
// 如果你想要获取进度更新,需要指定 `body: new ProgressEvent()`
body: new ProgressEvent()
}).then(response => {
const contentLength = response.headers.get('Content-Length');
return response.body.getReader({ mode: 'byob' }).then(reader => {
let received = 0;
const reader = response.body.getReader();
const total = contentLength ? Number(contentLength) : null;
return streamBlobFromReader(reader, total, (chunk) => {
received += chunk.byteLength;
console.log((received / total * 100).toFixed(2) + '%');
// 更新进度条的逻辑
});
});
});
function streamBlobFromReader(reader, total, onProgress) {
const contentType = response.headers.get('Content-Type');
const blob = new Blob([], { type: contentType });
const writer = new BlobWriter(blob);
return reader.enqueue().then(() => {
return writer.getBlob();
});
}
class BlobWriter {
constructor(blob) {
this._blob = blob;
this._writer = new BlobWriter.Writer(blob);
}
getBlob() {
return this._writer.getBlob();
}
enqueue(chunk) {
return this._writer.write(chunk).then(() => {
// 更新进度条的逻辑
});
}
}
注意:以上代码示例中的 // 更新进度条的逻辑
需要替换为你的实际更新进度条的逻辑。AJAX 示例中的 updateProgress
函数会在事件发生时被调用,并且你可以在该函数中更新进度条。FETCH 示例中,你需要使用实际的DOM操作来更新进度条。
评论已关闭