What's the equivalent to making this call eval('('+responseText+')')
in jQuery? I also understand that eval
is not that safe, so I'm looking for something safer and more idiomatic in jQuery.
5 Answers
Are you actually looking to execute Javascript code (which will always be unsafe to some extent), or are you trying to parse JSON from a string into an object?
If the former, eval() is still going to be your best bet.
If the latter, jQuery will do it for you as part of an AJAX request, or you can use a dedicated JSON plug-in to convert between string and object without the risk of executing arbitrary code.
a) To load and execute JS code:
$.getScript( url, [ success(data, textStatus) ] )
see http://api.jquery.com/jQuery.getScript/
b) To parse JSON:
$.parseJSON( json )
I don't think it's true that there are no browser differences. I just ran across one today. If you eval a string that calls a method on an object that doesn't exist, Firefox returns undefined and IE6 throws a TypeError.
By design jQuery sets out to improve browser implementations. Since there aren't problems with the way different browsers implement eval
it is not addressed by jQuery.
$.globalEval()
?
http://api.jquery.com/jQuery.globalEval/
Documentation says that it behaves quite differently than eval()
, but its the closest match if you want to pass your evals via jQuery.