javascript - 将索引发送到 XMLHttpRequest onLoad() 结果仅使用所有 onLoad() 的最后一个索引

标签 javascript ajax

当我将索引值传递给 onLoad() 时,因此当它开始在后台运行时,它将使用索引值来索引数组。问题是,从表面上看,当 onLoad() 开始运行时,它引用的索引值始终是最后一个索引。

我尝试将每个请求 (XMLHttpRequest) 属性设置为 onLoad() 启动时应使用的索引。

    setXMLOnLoad (request, index, chart) {

        let lenOfEachArray = this.lenOfEachArray;
        const wrapSensorArray = (index) => {return this.getSensorArray(index)};
        const wrapSetSensorArray = (index, data) => {this.setSensorArray(index, data);};

        //request.op = new Number(index);
        request.op = index;
        console.log(request.op); // reports 0 then 1 (fine)

        request.onload = function () {
            let sIndex = request.op; // reports 1 every time! (not fine)
            console.log(sIndex);
        }
    }

    createXMLRequests (chart) {
        this.XMLRequestsArray = new Array(this.getNum()).fill(new XMLHttpRequest());

        this.XMLRequestsArray.forEach((request,index) => {
            this.setXMLOnLoad(request, index, chart);
        });
    }

    sendXMLRequests (link) {
        this.XMLRequestsArray.forEach((request, index) => {

            let id = index + 1;
            let finalLink = link.concat(`${id}`);

            request.open("GET", finalLink);
            request.send();            
        });
    }

期望 request.op 在 onLoad() 中返回预先分配的正确索引值。

最佳答案

更新答案

问题是 fill(new XMLHttpRequest()) 实际上只创建一个被覆盖的 XMLHttpRequest 实例,从而取消之前的 http 调用。当您在检查器中打开网络选项卡时,您可以看到这一点:只有一个请求通过,其他请求被取消。

这个小片段发送了 4 个 http 请求,所以你想要的仍然是可能的,希望你可以用它来调整你的代码!

function createXMLRequests () {
  let XMLRequestsArray = [new XMLHttpRequest(), new XMLHttpRequest(), new XMLHttpRequest()]

  XMLRequestsArray.forEach((request,index) => {  
    request.onload = function () {
      console.log("request fulfilled");
      console.log(index)  
    }
    request.open("GET", "http://localhost/test.php");
    request.send();  

  });
}


createXMLRequests()

关于javascript - 将索引发送到 XMLHttpRequest onLoad() 结果仅使用所有 onLoad() 的最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55552053/

相关文章:

javascript - Ajax 成功需要一些 php JSON 对象

javascript - 基本的 jquery 延迟使用与 ajax

ajax - 在进行中的 Ajax 请求时重新加载页面给出空响应和状态为零

javascript - 无法从 JSON 请求中获取数据,尽管我知道它已返回

javascript - TypeAhead.js 没有显示任何输出 Rails?

php - Ajax调用面临尴尬局面

javascript - Uncaught ReferenceError : tankperson is not defined

SSRS 中的 JavaScript 无法正确处理数字符号

javascript - p5js 上的特定闪烁

javascript - 写Javascript时如何处理IE