views:

339

answers:

4

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?

A: 

If you set innerHtml of div, the script tags should execute. I am using $("#divid").load() to load dynamic contents and script tags do execute.

Try using JQuery if it does not work out using plain javascript.

jatanp
Sadly that isnt the case. Script in the html payload of an Ajax delivered payload to the client is not executed.
BahaiResearch.com
+1  A: 

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.

Chetan Sastry
+2  A: 

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)

Caleb
jQuery though needs to be triggered and if I included this in the payload that is sent back to the client it won't run as ajax downloaded script does not start. Exception: I can set the defer tag in the script markup and IE will run it, but that is only x% of the users.
BahaiResearch.com
+1  A: 

Hi,

I guess, you are writing script tag into innerHTML directly

This will not work.

document.body.innerHTML+="<script>alert(1)</scr"+"ipt>";

you have to write using DOM functions like this

var tag = document.createElement("script");
tag.innerHTML="alert(1)";
document.body.appendChild(tag); //can be append to any object other than body

or Better use jQuery

S.Mark
The problem is that the script is included in the Ajax payload and sent to the client inside the DIV. I can't get script to start once it arrives at the client so there is a chicken and egg problem.
BahaiResearch.com
Here's the site: http://BiblePro.BibleOcean.com (I write interfaith tools for all the world's religions)
BahaiResearch.com
Hi, in Ajax return, what kind of result? just javascript codes? or include script tag? If just javascript codes, you can `eval` or if include script tag, you can use above example in my post and change `document.body` with your div tag, and append there.
S.Mark
and could you update your post with more information, like your web site and more explanations? because people will notice and they will also can find out your current problem, rgds
S.Mark