jQuery uses (new Function(“return ” + data))(); instead of eval(data); to parse JSON, why?

后端 未结 3 889
后悔当初
后悔当初 2020-12-03 10:43

This link shows you that jQuery uses (new Function(\"return \" + data))(); for older browsers, to parse a JSON string instead of eval().

Wh

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 11:20

    http://www.json.org/js.html

    The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

    What exactly do you mean with safe? At least malicious code is not executed ;)

    See also: Alternatives to JavaScript eval() for parsing JSON

    Another point might be, that new Function() is considered to be a little faster than eval.

    Update:

    You can basically read about the same arguments in the comments on jQuery's .parseJSON() function.

提交回复
热议问题