3

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?

Taras Bulgakov
  • 543
  • 3
  • 11
  • 21

2 Answers2

3

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);
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
1

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/

Stephen Wood
  • 806
  • 5
  • 5