有没有办法让AJAX成功加载内联脚本函数?
我似乎无法弄清楚为什么这不起作用。我试图用AJAX渲染页面并成功渲染页面;但是,除非我在父文档中声明了一个javascript函数,否则我无法使内联脚本工作。我生成了一个与我试图完成的相关的简单示例。
<小时/> 家长文件
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function loadChild(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("childContent").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./child.html", true);
xhttp.send();
}
</script>
</head>
<body>
<input type='button' value='Load Child' onclick='loadChild();'/>
<div id='childContent'>
</div>
</body>
</html>
<小时/> 儿童文件
<input type='button' value='Child Function' onclick='childFunction();'/>
<script type='text/javascript'>
function childFunction(){
alert('Do something');
}
</script>
<小时/> 我试图通过PHP创建一个自适应框架,我可以用于我的整个站点并使用AJAX调用子站点加载;但是,要使其正常运行,我必须在调用每个页面之前渲染父文档中的每个函数。我想知道是否有办法让AJAX成功加载内联脚本函数?
答案 0 :(得分:1)
在这种情况下,我使用两种技术来做到这一点,
例如
$.getScript( "child.js", function( data, textStatus, jqxhr ) {
//add this script to the document
});
这里只加载了child.js,然后将其添加到文档DOM(Script DOM)中,并执行写在child.js文件中的javascript函数。
请参阅堆栈溢出中的这个问题:Javascript Inserted inside DOM。您需要在child.html代码中的javascript中使用eval()函数来执行DOM
谢谢,祝你好运:)