我有一個從 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();
}
} ```
uj5u.com熱心網友回復:
看起來安德烈亞斯是對的。
嘗試const ajaxRequest = ...代替var ajaxRequest = ....
我很難詳細解釋這里發生的事情。我的猜測如下:
如上所述,您使用相同的 ajaxRequest,就好像它會在 for 回圈之前宣告一樣。
其次,由于請求是異步的,它會在主執行緒代碼完成后從事件回圈發送。這意味著它將請求發送到 id = 4 兩次。
我仍然可能在細節上出錯(如果我錯了,請糾正我),但是將 var 更改為 const 應該會有所幫助。你試過嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/367742.html
