Two common solutions to undefined problems in front-end JSON acquisition

A friend from the blog Park answered:

Why add "(" ("+ data +")); / / "to eval?

The reason lies in the problem of Eval itself. Because JSON starts and ends with "{}", in JS, it will be

It is treated as a statement block, so it must be forcibly converted into an expression.

The purpose of parentheses is to force the eval function to force the expression in parentheses when processing JavaScript code

(expression) is converted to an object, not executed as a statement. For example, for

Like the literal {}, if the outer parentheses are not added, Eval will recognize the braces as the beginning and end of the JavaScript code block

End tag, then {} will be considered to have executed an empty statement. Therefore, the following two execution results are different:

alert(eval("{}"); // return undefined

alert(eval("({})");// return object[Object]

For this writing method, you can see it everywhere in JS.

For example: (function ()) {} (); When doing closure operation, etc.

Note: the framework used in this example is Spring + spring MVC + mybatis plus

Mybatis plus is an enhanced version of existing mybatis. The official website is: http://mp.baomidou.com

Here are more details

Code generator reference: Renren open source http://www.renren.io/

The above open source framework is of great help to improve development efficiency

Login verification example (successful example):

Failure example:

Two examples are compared. The former can successfully return JSON data, while the latter returns undefined data

And when you put data Returnmsg or data The returnmsg after the returncode is removed from the returncode, and the data can be returned by direct alert (data)

The returned data is directly in the form of JSON string (JSON string {}), and JSON is not formatted, so directly fetching the data leads to undefined

There are two ways to format JSON:

Mode 1:

One is the above var JSON = Eval ("(" + data + ")"); It is called parsing with eval

Mode 2:

var json = "{user:'user'}"

Var obj = new function ("return" + JSON) / / converted JSON object

alert(obj.name);

alert(obj.age);

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>