I have a div tag which is filled with script via an ajax call, but the script does not execute.
Is there a way to cause the script to execute?
The “script” tag JavaScript programs can be inserted almost anywhere into an HTML document using the <script> tag. You can run the example by clicking the “Play” button in the right-top corner of the box above. The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag.
AJAX is not a programming language. AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)
jQuery - AJAX load() Method The load() method loads data from a server and puts the returned data into the selected element. Syntax: $(selector). load(URL,data,callback);
You can add <script></script> inside a DIV tag. Just check on w3c, it is valid HTML.
If you use jQuery's .html
method it parses out the script tag and evals it:
$("div").html('<script type="text/javascript">alert("This should work")</script>');
If jQuery isn't an option you could write this yourself using either (1) a regular expression, or (2) parse out the DOM tree and find script tags. (#2 is how jQuery does it)
It is always a good idea to separate content from code. Load content via AJAX and code by inserting <script>
tags. If you are using jQuery, use $.getScript()
to load scripts dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With