动态创建的脚本不执行

时间:2014-06-14 16:42:49

标签: javascript ajax

我将一个脚本标记以及一堆其他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都会应用到文档中,包括脚本,但它没有运行,我没有弹出这个警告。可能导致这种情况的原因是什么?

3 个答案:

答案 0 :(得分:1)

检查以下代码段并将该功能称为

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]);
  }
};

答案 1 :(得分:0)

当您以这种方式将其推入DOM时,它将不会执行。你能用jQuery吗?它会执行它:

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

答案 2 :(得分:0)

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

相关问题