eval and new Function

[size=large][size=large][size=x-large][size=large][size=medium]jquery ajax After specifying the dataType as json, if the return value of the callback function cannot be converted to json, an error will be entered . You can use the eval and new Function() methods to convert json type strings to json objects.
eval("("+json+")")

(new Function("","return "+json))()


Why do you need to add "("("+data[size=large][/size]+")");//" to eval?
The reason is: the problem of eval itself. Since json starts and ends with "{}", in JS, it will be treated as a statement block, so it must be converted into an expression.
The purpose of adding parentheses is to force the eval function to convert the parenthesized expression (expression) into an object when processing JavaScript code, rather than as a statement (statement). For example, for an object literal {}, if no outer brackets are added, eval will recognize the curly brackets as the start and end tags of a JavaScript code block, and {} will be considered as executing an empty statement.

So the following two execution results are different:
alert(eval_r("{}"); // return undefined
alert(eval_r("({})");// return object[Object]


Why can new Function() convert objects?
function sayHi(sName, sMessage) {
  alert("Hello " + sName + sMessage);
}

can be converted to the following form:
have sayHi
=
new Function("sName", "sMessage", "alert(\"Hello \" + sName + sMessage);");

Then, (new Function("","return " + json))() is the following meaning:
(function xx(){
  return json;
})()

Since json is a string, after splicing with return, "{'a':1,'b':2}"==> "return {'a':1,'b':2}" after the execution of the
self-executing function , return json object[/size][/size][/size][/size][/size]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326604983&siteId=291194637