var emps; function GetEmps(){ const Http = new XMLHttpRequest(); const url='http://127.0.0.1:3001/GetEmployeeList'; Http.open("GET", url); Http.send(); Http.onreadystatechange = (e) => { e.preventDefault(); if(Http.responseText.length>0) { emps=JSON.parse(Http.responseText); for(let i=0;i<emps.length;i++) { CreateElementsInPage(i); } } } } function CreateElementsInPage(id) { console.log(id); var btn = document.createElement("BUTTON"); btn.innerHTML = emps[id].name; document.body.appendChild(btn); var newLine=document.createElement("br"); document.body.appendChild(newLine); } GetEmps();
i am trying to create buttons dynamically. for every item in emps array, I want a button to appear in the DOM, but the "CreateElementsInPage" functions get called 4 times instead of 2 (suppose I have 2 items in emps) and I get 4 buttons
You should check request state inside your callback:
Http.onreadystatechange = (e) => {
if(Http.readyState === XMLHttpRequest.DONE ) {
// Request is complete, do your logic
}
}
onreadystatechange
event function is triggered/called whenever the state of the connection is changed ( readyState
).
So you need to make sure that you create your button only when the connection is successful (done).
function GetEmps(){
const Http = new XMLHttpRequest();
const url='http://127.0.0.1:3001/GetEmployeeList';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
// Make sure that the request is done before calling your button creation method
if (Http.readyState === XMLHttpRequest.DONE) {
if(Http.responseText.length>0)
{
emps=JSON.parse(Http.responseText);
for(let i=0;i<emps.length;i++)
{
CreateElementsInPage(i);
}
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.