jQuery 中与 eval( ) 等效但更惯用的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/592392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:25:06  来源:igfitidea点击:

What's the equivalent but more idiomatic to eval( ) in jQuery?

jquery

提问by cathat

What's the equivalent to making this call eval('('+responseText+')')in jQuery? I also understand that evalis not that safe, so I'm looking for something safer and more idiomatic in jQuery.

eval('('+responseText+')')在 jQuery 中进行此调用的等价物是什么?我也明白这eval不是那么安全,所以我在 jQuery 中寻找更安全和更惯用的东西。

回答by Luke Dennis

Are you actually looking to execute Javascript code (which will always be unsafe to some extent), or are you trying to parse JSONfrom a string into an object?

您实际上是想执行 Javascript 代码(这在某种程度上总是不安全的),还是试图将JSON从字符串解析为对象?

If the former, eval() is still going to be your best bet.

如果是前者, eval() 仍然是你最好的选择。

If the latter, jQuery will do it for youas part of an AJAX request, or you can use a dedicated JSON plug-into convert between string and object without the risk of executing arbitrary code.

如果是后者,jQuery 将作为 AJAX 请求的一部分为您完成,或者您可以使用专用的JSON 插件在字符串和对象之间进行转换,而无需执行任意代码的风险。

回答by thorn?

a) To load and execute JS code:

a) 加载和执行 JS 代码:

$.getScript( url, [ success(data, textStatus) ] )

see http://api.jquery.com/jQuery.getScript/

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

b) To parse JSON:

b) 解析 JSON:

$.parseJSON( json )

see http://api.jquery.com/jQuery.parseJSON/

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

回答by cathat

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.

我认为没有浏览器差异是真的。我今天刚碰到一个。如果您对调用不存在对象的方法的字符串求值,Firefox 将返回 undefined 并且 IE6 抛出 TypeError。

回答by Ken Browning

By design jQuery sets out to improve browser implementations. Since there aren't problems with the way different browsers implement evalit is not addressed by jQuery.

根据设计,jQuery 着手改进浏览器实现。由于不同浏览器的实现eval方式没有问题,jQuery 没有解决它。

回答by Vikrant Chaudhary

$.globalEval()?

$.globalEval()?

http://api.jquery.com/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 evalsvia jQuery.

文档说它的行为与 完全不同eval(),但如果你想通过 jQuery传递你的评估,它是最接近的匹配。