动态创建的脚本未执行

Dynamically created script not executing

本文关键字:执行 脚本 创建 动态      更新时间:2023-09-26

我正在添加一个脚本标记,以及一堆其他html,到我的当前文档,从ajax调用检索。由于某些原因,脚本没有运行

//Response handling function
function(responseText){
    document.getElementById('reportContainer').insertAdjacentHTML('afterbegin',responseText);
}

responseText内容示例:

<h2>You are <em class="won">victorious</em>!</h2>
<h3>Earnings</h3>
... 
<script>
    alert('dgd');
</script>

所有的html都被应用到文档,包括脚本,但它没有运行,我没有得到这个警告弹出。是什么原因造成的呢?

检查下面的代码片段并将函数调用为

var newEle = document.querySelector("#reportContainer");
exec_body_scripts(newEle);

函数
exec_body_scripts = function(body_el) {
  // Finds and executes scripts in a newly added element's body.
  // Needed since innerHTML does not run scripts.
  //
  // Argument body_el is an element in the dom.
  function nodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toUpperCase() ===
              name.toUpperCase();
  };
  function evalScript(elem) {
    var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        script = document.createElement("script");
    script.type = "text/javascript";
    try {
      // doesn't work on ie...
      script.appendChild(document.createTextNode(data));      
    } catch(e) {
      // IE has funky script nodes
      script.text = data;
    }
    head.insertBefore(script, head.firstChild);
    head.removeChild(script);
  };
  // main section of function
  var scripts = [],
      script,
      children_nodes = body_el.childNodes,
      child,
      i;
  for (i = 0; children_nodes[i]; i++) {
    child = children_nodes[i];
    if (nodeName(child, "script" ) &&
      (!child.type || child.type.toLowerCase() === "text/javascript")) {
          scripts.push(child);
      }
  }
  for (i = 0; scripts[i]; i++) {
    script = scripts[i];
    if (script.parentNode) {script.parentNode.removeChild(script);}
    evalScript(scripts[i]);
  }
};

当您以这种方式将它推送到DOM中时,它将不会执行。你会使用jQuery吗?它将执行它:

$('#reportContainer').append('<script type="text/javascript">alert(123);</script>');

您从ajax调用中得到的是纯文本或XML,可以作为HTML片段插入DOM,但出于安全原因,所有javascript代码都被明确禁止。有很多选择可以解决这种情况—从提取responseText中的部分和使用eval方法(不推荐,不好的做法)到使用jQuery。加载方法。