Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery. How to execute script loaded from JSON?

I have file like this:

{'html' : '<div id="bla">something</div>',
 'script' : ' $().ready(function() { /* some code */});' }

I need to load it with jQuery and execute the 'script' variable. I know about $.getScript, but I need to run the script not from URL, but from part of JSON file. Otherwise I would need to do 2 heavy requests to server instead of one (javascript code is not static).

Is there a way to do so?

like image 766
Taras Bulgakov Avatar asked May 15 '26 06:05

Taras Bulgakov


2 Answers

At first parse:

var obj = $.parseJSON(jsonString);

Then prepare div for HTML:

<div id="forHtml">
</div>

And run your code:

$('#forHtml').html(obj.html);
eval(obj.script);
like image 105
Sergey Metlov Avatar answered May 17 '26 06:05

Sergey Metlov


You can either use JavaScript's eval(script), or the jQuery.globalEval(script) if you need to:

http://www.w3schools.com/jsref/jsref_eval.asp

http://api.jquery.com/jQuery.globalEval/

like image 42
Stephen Wood Avatar answered May 17 '26 06:05

Stephen Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!