javascript - 通过 Ajax 在内部加载带有 JS 代码的外部 HTML 代码
问题描述
我的 HTML 页面通过 onclick-event 外部 HTML 代码加载,其中 JS 代码位于 div 框中。JS代码没有被执行。
简化示例:
index.php
// Full HTML document with the XMLHttpRequest() to extern.php
外部文件
<?php
header("Content-type: text/html; charset=utf-8");
$concat = '<div>many HTML content generated with PHP.</div>';
$concat .= '<script>';
$concat .= 'console.log("TEST");'; // In original the script modified the HTML above.
$concat .= '</script>';
echo $concat;
?>
带有脚本的外部内容被加载到 div-box 中,没问题。
问题:console.log("TEST")
不工作。
请仅使用纯 Javascript 的解决方案。请不要使用 JQuery 或类似的。
编辑:没有其他问题有 Ajax 的解决方案,但仅适用于innerHTML
.
解决方案:
- 在外部内容中写一个
<script>
标签,其中包含将要执行的 Javascript 代码。 - 在 XMLHttpRequest (Ajax) 中将外部内容传递给一个
function()
. - 在
function()
: -
- 通过 . 在 HTML 文档中插入外部内容
innerHTML
。
- 通过 . 在 HTML 文档中插入外部内容
-
innerHTML
从<script>
外部内容中的标签中获取。
-
- 使用
<script>
-执行。innerHTML
eval()
- 使用
提示:仅function()
在外部内容<script>
标签中使用 a。这function()
将通过通过 Ajax 加载外部内容来触发。将其保存function()
在 HTML 文档或单独的 *.js 文件中,并将其嵌入到 HTML 文档中。
在职的:
- 带有
custom_function()
javascript(用于操作外部内容)的 a 保存在customscript.js
. customscript.js
嵌入在 HTML 文档中。- 当 XMLHttpRequest() 被调用时
-
- 请求外部内容。
-
- 外部内容通过 .insert_function() 传递给
innerHTML
。
- 外部内容通过 .insert_function() 传递给
-
- 插入函数():
-
-
innerHTML
通过在 HTML 文档中插入外部内容。
-
-
-
- 例子:
-
-
-
-
var ajaxcontent = document.getElementbyId("extern-content");
-
-
-
-
-
ajaxcontent.innerHTML = external_content;
-
-
-
-
innerHTML
从外部内容<script>
标签中获取并执行它。
-
-
-
- 例子:
-
-
-
-
eval(ajaxcontent.getElementsByTagName("script")[0].innerHTML);
-
-
编辑: 重复???(失败)
链接的问题是:“可以用 innerHTML 插入脚本吗?”。我的问题不会插入!应该抓取脚本内容并对其进行评估。
解决方案
推荐阅读
- selenium-ide - 右键单击以使用 Selenium IDE 访问子菜单
- python - 如何迭代具有 3 个变量的函数?
- angular - PrimeNg MenuItem 在禁用时仍然可以点击
- python - 想要使用 for 循环多次运行查询并将每个结果添加到字典中。此代码仅在循环时执行一次
- postgresql - PGAgent 作业未插入远程数据库
- python - Python Pandas 比较 2 数据帧
- javascript - yup 条件验证
- python - 如何使用 python psycopg2 从 postgres 表中获取列名?
- keras - 使用 DL4J 加载 Keras 模型时 KerasConvolution1d.java 中的 InvalidKerasConfigurationException
- python - 更新表按钮的 Onclick 想要在 Django 中将表单显示为弹出窗口