相同的数据会向JavaScript表添加两次,而不是向表添加两个不同的东西



我有一个程序,它从API中提取并在表中显示结果。应该发生的是,每一行都应该是不同的数据。然而,当运行此操作时,它会两次添加ID为4的数据,完全跳过ID为3的数据。起初,我想我一定是在GET请求上搞砸了什么。我去检查了一下,结果发现它正在获取数据,但没有将其添加到表中。我在for循环中移动了所有要添加到表中的代码,但也出现了同样的问题。如果有任何用途的话,我将使用Tomcat来处理API。

附件是我用来向表中添加行的函数。

function addRow(tableName, rowData) {
for (var h = 0; h < rowData.length; h++) {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(ajaxRequest.status == 200){
let table = document.getElementById(tableName);
let row = table.insertRow(1);
var order = JSON.parse(ajaxRequest.responseText);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
var cell8 = row.insertCell(8);
var cell9 = row.insertCell(9);
var cell10 = row.insertCell(10);

cell0.innerHTML = order.id;
cell1.innerHTML = order.name;
cell2.innerHTML = order.time;
cell3.innerHTML = order.type;
cell4.innerHTML = order.creamerAmount + " " + order.creamerType;
cell5.innerHTML = order.sugarAmount;
cell6.innerHTML = order.coffeeType;
cell7.innerHTML = order.teaType;
cell8.innerHTML = order.hotChocolateType;
cell9.innerHTML = order.smoothieType;
cell10.innerHTML = order.protein;
} else {
//I'm aware this is bad, not sure how to handle it otherwise though...
h--;
}
}           
}
ajaxRequest.open('GET', 'http://localhost:13760/cafe/cafe/orders/' + rowData[h]);
ajaxRequest.send();
}

}   ```

看起来Andreas是对的
请尝试const ajaxRequest = ...而不是var ajaxRequest = ...

我很难详细解释这里发生的事情。我的猜测如下:
如上所述,您使用相同的ajaxRequest,就好像它将在for循环之前声明一样
其次,由于请求是异步的,所以它是在主线程代码完成后从事件循环中发送的。这意味着它向id=4发送了两次请求。

尽管我在细节上可能会出错(如果我错了,请纠正我(,但将var更改为const应该会有所帮助。你试过了吗?

最新更新