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?
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)
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
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.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.
make a callback after ajax load completes like:
function load_scripts(element_id) {
if (!document.getElementById) return;
var elmt = document.getElementById(element_id);
if (!elmt) return;
var scripts = elmt.getElementsByTagName('script');
if (!scripts) return;
var file = null;
var fileref = null;
for (var i = 0; i < scripts.length; i++) {
file = scripts[i].getAttribute('src');
if (file) {
fileref = document.createElement('script');
fileref.setAttribute('type', 'text/javascript');
fileref.setAttribute('src', file);
document.getElementsByTagName('head').item(0).appendChild(fileref);
} else {
eval(scripts[i].innerHTML);
}
}
}
ScriptManager.RegisterClientScriptBlock. The framework sends them down specially forevaling on the client upon insertion into the DOM.