为什么浏览器不解析AJAX加载的文件中的JS代码? [英] Why doesn't browser parse the JS code in the file loaded by AJAX?
问题描述
我有2个文件,第一个文件有一些HTML和一部分JS。第二个文件是主文件,它通过'XmlHttpRequest'加载第一个文件。
第一个文件是这样的:
< div>
我的HTML内容
< / div>
< script id =my_js_block>
函数my_function(){
alert(9);
}
< / script>
第二个文件如下所示:
< div id =div_ajax_content>
& nbsp;
< / div>
< script>
函数load_ajax_content(){
//同步XmlHttpRequest(...,...,false);
//...load并将第一个文件放入'div_ajax_content'
}
load_ajax_content();
my_function(); < - 在此处失败
< / script>
如何解决这个问题?
通过innerHTML添加脚本不会运行脚本。因此,你的函数没有被定义,因此失败。
相反,我建议分别加载HTML和JS,并且使用DOM方法添加JS以将< script>
标记,或 eval()
来执行返回的文件内容。 $ b
I have 2 files, the first file has some HTML and a portion of JS. The second file is the main file, and it loads the first file thru' XmlHttpRequest.
The first file is like this:
<div>
My HTML contents
</div>
<script id="my_js_block">
function my_function() {
alert(9);
}
</script>
The second file is like this:
<div id="div_ajax_content">
</div>
<script>
function load_ajax_content() {
//synchronously with XmlHttpRequest(...,...,false);
//...load and throw the first file into 'div_ajax_content'
}
load_ajax_content();
my_function(); <-- fails here
</script>
How to solve this matter?
Adding a script via innerHTML does NOT run the script. Therefore your function is not being defined, hence the failure.
Instead, I suggest loading HTML and JS separately, and either appending the JS using DOM methods to put the <script>
tag on the page, or eval()
to execute the returned file contents.
这篇关于为什么浏览器不解析AJAX加载的文件中的JS代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!