一次多个XMLHttpRequests

时间:2015-03-11 23:03:21

标签: javascript php xmlhttprequest

我正在构建一个php上传器,我为每个选择上传的文件呈现了这个javascript。

        var formdata = new FormData();
        formdata.append("file1", file);

        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress", progressHandler, false);
        ajax.open("POST", "fileUploader.php");

        startTime = (new Date()).getTime();
        ajax.send(formdata);

我希望能够为每个请求更新不同的进度条;但是,我无法弄清楚如何做到这一点。

这是我的progresshandler函数

function progressHandler(event) {
document.getElementById("upProgress").value = event.loaded/event.total * 100;
}

如何动态选择进度条而不是始终选择" upProgress"酒吧?

新代码:

var pgb = function(div, progBar) {
            this.div = div;
            this.progBar = progBar;

            var _this = this;

            this.progressHandler = function(event) {
                _this.progBar.value = event.loaded/event.total * 100;
            }
            this.completeHandler = function(event) {
                _this.div.innerHTML += "...done";

                console.log(_this.progBar);
            }
        }

然后为每个文件完成以下操作。

var l_pbg = new pgb(document.getElementById('div_'+index), document.getElementById('up_'+index));

            var ajax = new XMLHttpRequest();
            ajax.upload.addEventListener("progress", l_pbg.progressHandler, false);
            ajax.addEventListener("load", l_pbg.completeHandler, false);
            ajax.addEventListener("error", errorHandler, false);
            ajax.addEventListener("abort", abortHandler, false);
            ajax.open("POST", "fileUploader.php");

            startTime = (new Date()).getTime();
            ajax.send(formdata);

现在的问题是,只有最后一个要上传的文件的进度条已更新;但是这两个文件都上传了。我可以看到progressHandler被称为all,但是当我在控制台中打印时,只有第一次更新是可视的吗?:

Console

Visual

1 个答案:

答案 0 :(得分:0)

您可以创建一个引用DOM元素的类,并具有progressHandler方法:

var Pgb =  function(elem) {
    this.elem = elem;

    var _this = this;
    this.progressHandler = function(event) {
        _this.elem.value = event.loaded/event.total * 100;
    }
}

然后为每个进度条创建此类的实例:

var pgb1 = new Pgb(document.getElementById("upProgress1"));
var pgb2 = new Pgb(document.getElementById("upProgress2"));

然后将该方法作为ajax事件监听器的处理程序传递:

ajax.upload.addEventListener("progress", pgb1.progressHandler, false);
ajax.upload.addEventListener("progress", pgb2.progressHandler, false);

这里的工作示例:https://jsfiddle.net/rrun9ftz/