简体   繁体   中英

Ajax load inline javascript

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.


PARENT DOCUMENT

 <!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>


CHILD DOCUMENT

 <input type='button' value='Child Function' onclick='childFunction();'/> <script type='text/javascript'> function childFunction(){ alert('Do something'); } </script>


I am trying to create an adaptive framework via PHP that I can use for my whole site and call the sub-sites using AJAX to load; however, to get this to currently function correctly, I am having to render every function in the parent document prior to calling each page. I want to know if there is a way to get AJAX to successfully load inline script functions?

I such cases I use two techniques to do this,

  1. Using jQuery to use getscript() function to load a new script, which will automatically execute the script.

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.

  1. Another way to do this is to add this whole code to DOM. JavaScript inserted as DOM text will not execute. But you can use dynamic script pattern to execute the new Javascript code.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM