0

I have an HTML with JS element that I need to load on runtime.

These are some example files to illustrate the functionality I'm looking for.

File 1: index.html

<div id="mydiv"> </div>
<script type="text/javascript">
   xmlhttp=new XMLHttpRequest();
   xmlhttp.open("GET","script.php",false);
   xmlhttp.send();
   var text=xmlhttp.responseText;
   var elem=document.getElementById("mydiv")
   elem.innerHTML=text
   func() 
</script>    

File 2: script.php

<script type="text/javascript">
   function func(){
       alert("func")
   }
</script>

ERROR returned by browser:

Inline script thread
Uncaught exception: ReferenceError: Undefined variable: func Error thrown at line 20, column 0 in localhost/my_project/: func()

4

1 回答 1

0

.innerHTML不执行 html 中的脚本元素。

尝试这个:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","script.php",false);
xmlhttp.send();
var text=xmlhttp.responseText;

var root = document.createElement("div");
root.innerHTML = text;
var scripts = root.getElementsByTagName("script");

for( var i = 0; i < scripts.length; ++i ) {
    var code = scripts[i].innerText || scripts[i].textContent || scripts[i].innerHTML || "";
    eval(code);
}

func();
于 2012-11-04T11:27:23.417 回答