Search code examples
jqueryajaxjsongetscript

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?


Solution

  • 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);