Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading script tags via AJAX

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?

like image 300
Ian Vink Avatar asked Nov 25 '09 23:11

Ian Vink


People also ask

How do I run a script tag?

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.

Can I use JavaScript in AJAX?

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)

How do I load AJAX?

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);

Can I add script tag inside div?

You can add <script></script> inside a DIV tag. Just check on w3c, it is valid HTML.


2 Answers

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)

like image 146
Caleb Avatar answered Sep 22 '22 07:09

Caleb


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.

like image 37
Chetan S Avatar answered Sep 22 '22 07:09

Chetan S