There's a div called "Content":
<div id="content"></div>
It should be filled with data from a PHP file, by AJAX, including a <script>
tag. However, the script inside this tag is not being executed.
<div id="content"><!-- After AJAX loads the stuff that goes here -->
<script type="text/javascript">
//code
</script>
<!-- More stuff that DOES work here -->
</div>
This 'just works' for me using jQuery, provided you don't try to append a subset the XHR-returned HTML to the document. (See this bug report showing the problem with jQuery.)
Here is an example showing it working:
Here is the equivalent of the above: http://jsfiddle.net/2CTLH/
JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the
src
attribute of your script tag and voila, it loads and executes the external script.This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.
I used this code, it is working fine
This worked for me by calling eval on each script content from ajax .done :
My conclusion is HTML doesn't allows NESTED SCRIPT tags. If you are using javascript for injecting HTML code that include script tags inside is not going to work because the javascript goes in a script tag too. You can test it with the next code and you will be that it's not going to work. The use case is you are calling a service with AJAX or similar, you are getting HTML and you want to inject it in the HTML DOM straight forward. If the injected HTML code has inside SCRIPT tags is not going to work.