Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, August 6, 2016

Dynamically added javascript with external script doesn't get executed

script.js

This is the OP's code modified to my specifications above (using appendChild instead of innerHTML, and the AJAX call returns the contents of api.html below)

function ajaxCall() {      //... some script to send ajax request which calls createDiv() after success      if (window.XMLHttpRequest){          xmlhttp=new XMLHttpRequest();      }      else{          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");      }      xmlhttp.onreadystatechange=function(){          if(xmlhttp.readyState==4&&xmlhttp.status==200){              createDiv(xmlhttp.responseText);          }      };      xmlhttp.open("GET","api.html");      xmlhttp.send();  }  function parseResponse(response) {      var parser = new DOMParser();      var dom = parser.parseFromString(response, "text/html");      return dom;  }  function createDiv(responsetext)  {      var dom = parseResponse(responsetext);        var _ws = dom.getElementById('styles');      var h = document.getElementsByTagName('head')[0];      h.appendChild(document.importNode(_ws, true));        var _jr = dom.getElementById('script1');      var _vc = dom.getElementById('script2');      var _rv = dom.getElementById('script3');        var _rw = dom.getElementById('my_div');      var _b = document.getElementsByTagName('body')[0];      var _d = document.createElement('div'); _d.id = 'just_id';        _d.appendChild(document.importNode(_jr, true));      _d.appendChild(document.importNode(_vc, true));      _d.appendChild(document.importNode(_rv, true));        _d.appendChild(document.importNode(_rw, true));      _b.appendChild(_d);  }  ajaxCall();  

api.html (returned by the AJAX call)

                                  

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.