开发者

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' varia开发者_Python百科ble. 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?


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


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜