Is there a way to get AJAX to successfully load inline script functions?
I can't seem to figure out why this is not working. I am attempting to render a page with AJAX and the page render successfully; however, unless I declare a javascript function in the parent document, I cannot get the inline script to work. I generated a simple example that is relative to what I am attempting to accomplish.
<!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>
I such cases I use two techniques to do this,
For Example
$.getScript( "child.js", function( data, textStatus, jqxhr ) {
//add this script to the document
});
Here only child.js is loaded, it is then added to the document DOM (Script DOM) and it executes the javascript functions written inside the child.js file.
Please refer to this question in stack overflow: Javascript Inserted inside DOM . You will required to use eval() function in your javascript inside child.html code for DOM to be executed
Thanks and best luck :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.