My HTML Page load via an onclick-event external HTML Code with JS code inside in a div-box. The JS code is not executed.
simplifyed Example:
index.php
// Full HTML document with the XMLHttpRequest() to extern.php
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;
?>
The external content with script are loaded in the div-box, no problem.
Problem: The console.log("TEST") dont work.
Please only solutions with pure Javascript. Please no JQuery or similar.
Edit: No other questions have a solution for Ajax, but only for innerHTML.
Solution:
- In the external content write a
<script>tag with inside your Javascript code that will be executed. - In the XMLHttpRequest (Ajax) passed the external content to a
function(). - In the
function(): -
- insert the external content in the HTML document via
innerHTML.
- insert the external content in the HTML document via
-
- get the
innerHTMLfrom the<script>tag in the external content.
- get the
-
- execute the
<script>-innerHTMLwith aeval().
- execute the
Tip: Use only a function() in the external content <script> tag. This function() will be triggerd by loading the external content via Ajax. Save this function() in the HTML document or in a separate *.js file and embedded it in the HTML document.
Working:
- a
custom_function()with javascript (for manipulating the external content) is saved in acustomscript.js. - the
customscript.jsis embedded in the HTML document. - when the XMLHttpRequest() is called
-
- the external content is requested.
-
- the external content is passed to a insert_function() with
innerHTML.
- the external content is passed to a insert_function() with
-
- the insert_function():
-
-
- insert the external content via
innerHTMLin the HTML document.
- insert the external content via
-
-
-
- example:
-
-
-
-
var ajaxcontent = document.getElementbyId("extern-content");
-
-
-
-
-
ajaxcontent.innerHTML = external_content;
-
-
-
-
- get the
innerHTMLfrom the external content<script>tag and execute it.
- get the
-
-
-
- example:
-
-
-
-
eval(ajaxcontent.getElementsByTagName("script")[0].innerHTML);
-
-
EDIT: Duplicate??? (fail)
The linked Question is: "Can scripts be inserted with innerHTML?". My question will NOT insert! It should be grabbed the script-content and eval it.