Executing <script> injected by innerHTML after AJAX call

JCOC611 picture JCOC611 · Jan 6, 2011 · Viewed 221.8k times · Source

There's a div called "Content":

<div id="content"></div>

It should be filled with data from a PHP file, by AJAX, including a <script> tag. However, the script inside this tag is not being executed.

<div id="content"><!-- After AJAX loads the stuff that goes here -->
   <script type="text/javascript">
     //code
   </script>
   <!-- More stuff that DOES work here -->
</div>

Answer

Firas Nizam picture Firas Nizam · Apr 29, 2013

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div