jquery - Dynamically generated Javascript returned via AJAX in JSON format will not execute when appended -



jquery - Dynamically generated Javascript returned via AJAX in JSON format will not execute when appended -

i have webpage makes ajax request php script. php script responds valid json object, , sets content-type header application/json.

the json format follows (as reported console.log(json.stringify(data)) data json response):

{ "content": "<script type=\"text/javascript\">console.log(\"test\");</script>" }

i create div class of "content" (remember data ajax responsetext json object):

var content = document.createelement("div"); content.setattribute("class", "content"); content.innerhtml = data.content;

finally, append content div existing div on site.

existingdiv.appendchild(content);

i examine source in elements tab of google chrome's developer tools because job of showing actual dom node, , text. script block shows dom node.

unfortunately, script not executed - console.log("test"); not output test developer tools console.

the alternative i've seen far utilize eval() i'm trying avoid plague. also, content might contain more script block. contain other html markup well.

what missing? how can dynamically added block of javascript execute?

a jquery solution acceptable.

a possible solution utilize new function() as:

$(document).ready(function(){ var script = "window.alert('hi')"; new function(script)(); });

as why script not executing, @pointy suggested (but not exclusively + way circumvent that), shown code:

<script type='text/javascript'> $(document).ready(function() { $("<script type='text/javascript'>window.alert('hi');<\/script>").appendto(document.body); // work var container = document.createelement("div"); // won't work container.innerhtml = "<script type='text/javascript'>window.alert('hi');<\/script>"; document.body.appendchild(container); var script = document.createelement("script"); // script.innerhtml = "window.alert('hi');"; document.body.appendchild(script); }); </script>

edit: added requested unit test: http://jsperf.com/eithed-hvsa

javascript jquery ajax

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -