简体   繁体   中英

document.getElementById innerHTML Not working in loop

Hy ! I am trying to put the result of an XMLHttpRequest inside a div using document.getElementById innerHTML without success.

In the head :

XMLHttpRequest is fine (I tried document.write and it show my results).

Here is my code :

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","http://www.mywebsite.com/my.php",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

for(var i=0; i < xmlDoc.getElementsByTagName("place").length; i++) {
name = xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue;
document.getElementById('name').innerHTML += name +"<br>"; 
}

In the body :

<div id="name"></div>

NB : my.php generate xml file and replacing the line document.getElementById... by document.write(name + "br tag"); is working fine.

Thanks in advance for help.

Ok, I found my mistakes and here is the working code :

    if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    xmlDoc=xmlhttp.responseXML;
    for(var i=0; i < xmlDoc.getElementsByTagName("place").length; i++) {
        var xmlName = xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue;
    document.getElementById('name').innerHTML += xmlName +"<br>"
    }
}
}
xmlhttp.open("GET","http://mywebsite.com/xmlcreate.php",true);
xmlhttp.send();

Thanks for helps !

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM