首页 > 解决方案 > 通过 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.
解决方案:

提示:仅function()在外部内容<script>标签中使用 a。这function()将通过通过 Ajax 加载外部内容来触发。将其保存function()在 HTML 文档或单独的 *.js 文件中,并将其嵌入到 HTML 文档中。

在职的:

编辑: 重复???(失败)
链接的问题是:“可以用 innerHTML 插入脚本吗?”。我的问题不会插入!应该抓取脚本内容并对其进行评估。

标签: javascriptxmlhttprequesteval

解决方案


推荐阅读