我想累积来自不同ajax调用的数据,然后将其显示在div中。现在我有这个:
//residents is an array of urls
function doResidentsRequest(residents) {
for(let i = 0; i < residents.length; i++) {
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
let residentData = JSON.parse(this.responseText);
displayResidents(residentData);
console.log(residentData);
}
};
let url = residents[i];
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
function displayResidents(residentsData) {
document.getElementById("modal-content").insertAdjacentHTML('beforeend', residentsData["name"]);
}
答案 0 :(得分:0)
尝试promise.all()函数。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all 另外从javascript获取api比xmlhttp更有效。