用于循环的xhr响应不工作

xhr response with for loop not working

本文关键字:工作 响应 xhr 循环 用于      更新时间:2023-09-26

我有带for循环的xhr,它在中非常罕见

for(var i = 0; i < this.files.length; i++) {
    var xhr = new XMLHttpRequest();
    xhr.upload.onprogress = function(e) {
    };
    xhr.onreadystatechange = function(e) {
        if(this.readyState === 4) {
            console.log(xhr.responseText);
        }
    };
    var formdata = new FormData();
    formdata.append("files", this.files[i]);
    console.log(this.files[i]);
    xhr.open('POST', 'slike.php');
    xhr.send(formdata);
}

我称之为slike.php。它运行得很好,但在responseText上,它不好,有时只从循环中获取最后一个文件,有时获取两个文件(具有相同文本)。我不知道该怎么解决,我到处找,找不到答案。

XHR默认情况下是异步的,因此除非您另有指定(XHR open()方法中的async=false),否则循环可能在第一个XHR初始化之前就已经完成。

但是循环中代码中的ithis.files[i])指的是循环中相同的i,因此当第一个XHR开始时,i可能被分配为this.files.length-1。这就是为什么你总是只得到最后一个文件。

这就是为什么您必须创建所谓的闭包,以确保您使用的索引是您真正想要使用的索引。

试试这个:

for (var i = 0; i < this.files.length; i++) {
    (function(index, files) { // In this closure : parameters of a function in JS 
                              // are available only in the function,
                              // and cannot be changed from outside of it
        var xhr = new XMLHttpRequest(); // variables declared in a function in JS
                                        // are available only inside the function
                                        // and cannot be changed from outside of it
        xhr.upload.onprogress = function (e) {
        };
        xhr.onreadystatechange = function (e) {
            if (this.readyState === 4) {
                console.log(xhr.responseText);
            }
        };
        var formdata = new FormData();
        formdata.append("files", files[index]); // `index` has nothing to do with `i`, now:
                                                // if `i` changes outside of the function,
                                                //`index` will not
        console.log(files[index]); // Don't keep `console.log()` in production code ;-)
        xhr.open('POST', 'slike.php');
        xhr.send(formdata);
    })(i, this.files)
}

或者如果真的想按顺序获取文件:

var i = 0,
    fileNb = this.files.length;
function getNextFile(file) {
    var xhr = new XMLHttpRequest();
    xhr.upload.onprogress = function (e) {
    };
    xhr.onreadystatechange = function (e) {
        if (this.readyState === 4) {
            console.log(xhr.responseText);
            if (++i < fileNb) getNextFile(this.files[i]);
        }
    };
    var formdata = new FormData();
    formdata.append("files", file);
    console.log(file); // Don't keep `console.log()` in production code ;-)
    xhr.open('POST', 'slike.php');
    xhr.send(formdata);
}
getNextFile(i);
console.log(xhr.responseText);

您正在访问xhr当前值(通常是最后创建的值),而不是事件处理程序所附加的对象。

使用this,而不是像前一行中那样使用xhr