AJAX(XMLHttpRequest)进度监控与Service Workers不兼容。

3

我想将一个 web 表单转换为离线工作。原本,用户完成每个步骤后,我会将表单信息存储在 Web 服务器上的 SQL 数据库中。其中一个步骤包括上传图片,我实现了一个进度条。

添加 Service Worker 后,我注意到进度条不再起作用(进度条会显示,但永远不会更新以显示已上传文件的百分比)。我在多个浏览器中进行了测试,以确保这不是浏览器相关的,并在所有浏览器中都得到相同的结果(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;
    }
})

这是我服务工作线程文件中处理fetch事件的代码。

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上没有找到这个问题,所以我要发布并回答自己的问题。如果有人对改进或更好的解决方案有任何意见,请告诉我。

2个回答

5

我在这里找到了答案我需要做的是让服务工作者忽略post请求。 我更新了我的服务工作者代码如下:

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.
                        }
                    });
            })
    );
});

0

如果您正在寻找一种进度条,可以告诉您使用服务工作者加载了多少内容到缓存存储中,那几乎是不可能的,因为 SW 没有访问 DOM 的权限。但是您可以从另一方面解决这个问题。请查看此 https://dev59.com/mKrka4cB1Zd3GeqPZShW#54222155,还有其他答案可以回答您的问题!干杯 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接