我想将网络表单转换为脱机工作。最初,我将在用户完成每个步骤后将表单信息存储在Web服务器上的sql数据库中。步骤之一包括上传图像,为此我实现了进度条。
添加服务人员后,我注意到进度栏不再起作用(该进度条将显示,但永远不会更新以显示已上传了多少文件)。我在多种浏览器中进行了测试,以确保它不依赖于浏览器,并且在所有浏览器(chrome,firefox,edge,safari,移动版本中)都具有相同的结果。
这是我的ajax请求的第一部分。
$.ajax({
type: "POST",
url: url,
datatype: "json",
data: JSON.stringify(data),
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = getCurrentProgress(evt.loaded, evt.total);
$("#progressBarContainer .progress > .progress-bar").css({ "width": percentComplete + "%" });
$("#progressBarContainer .progress > .progress-bar .percent-complete").text(percentComplete + "%");
}
}, false);
return xhr;
}
})
这是我的服务工作者文件中用于处理提取事件的代码。
self.addEventListener("fetch", event => {
event.respondWith(
caches.open(staticCacheName)
.then(cache => {
return cache.match(event.request)
.then(response => {
if (response) {
return response;
}
else {
return fetch(event.request);
}
});
})
);
});
我能够找到一个解决方案,但在stackoverflow上找不到此问题,因此我要发布并回答我自己的问题。如果有人对改进或更好的解决方案有任何意见,请告诉我。
答案 0 :(得分:0)
我找到了答案here。我需要做的是让服务人员忽略发布请求。我将服务人员代码更新为:
self.addEventListener("fetch", event => {
//This is the code that ignores post requests
if (event.request.method === "POST") {
return;
}
event.respondWith(
caches.open(staticCacheName)
.then(cache => {
return cache.match(event.request)
.then(response => {
if (response) {
return response; //The URL is cached
}
else {
return fetch(event.request); //Go to the network.
}
});
})
);
});
答案 1 :(得分:0)
如果您正在寻找一个进度条,该进度条可以告诉您使用Service Worker已将多少内容加载到缓存存储中,则几乎是不可能的,因为SW无法访问DOM。但是,您可以从另一方面解决这个问题。请查看此https://stackoverflow.com/a/54222155/9900456,以及您问题的其他答案!干杯:)