-->

AppendChild not working in Ajax request

2020-03-08 06:07发布

问题:

I have a script to add an input field element when a current one is pressed. When i use innerHTML it replaces the current, which is not what i want. So I figured appendChild should add and not replace, but its not working. Heres my script..

<script type="text/javascript">
function addfile()
{
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)
    {
    document.getElementById("org_div1").appendChild = xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","addfile.php");
xmlhttp.send();
}
</script>

And my html content..

<div id="org_div1" class="file_wrapper_input">

                        <input type="hidden" value="1" id="theValue" />
<input type="file" class="fileupload" name="file1" size=
"80" onchange="addfile()" /></div>

And my addfile.php file..

    var i=0;
        var ni = document.getElementById('org_div1');
        var numi = document.getElementById('theValue');
        var num = (document.getElementById('theValue').value -1)+ 2;
        numi.value = num;
        var divIdName = num;
</script>
<input type="file"  class="fileupload" size="80" name="file' + (num) + '" onchange="addfile()" />;

Any input? Again, innerHTML DOES work, appendChild does not. Thanks.

回答1:

parent.appendChild() is a function waiting for DomNode Object and you are passing a String, it can't work...

Try :

var d = document.createElement('div');
d.innerHtml = xmlhttp.responseText;
document.getElementById("org_div1").appendChild(d);


回答2:

AppendChild expects an object, where innerHTML works with a String. And since your server returns partial HTML, this will only work with innerHTML.