Talk about the use of the built-in function eval () for JS.
It was originally used to convert a JSON-formatted string sent from the background into a JSON object. It turned out to be really powerful, much more than that, but today it's just about it. If you want to know more about the next W3school can be referred to.
To get to the point:
Java code
<script>
var json='{"id":1}';
alert(json.id);
</script>
If you look carefully, you can see that the above Code pop-up dialog box is not to show the ID. The reason is that JSON is just a string object, not a true JSON object, and notice the outermost two single quotes.
Java code
<script>
var json={"id":1};//去掉单引号
alert(json.id);
</script>
With the single quotation mark removed, the ID is displayed successfully. The JSON at this point is a JSON object.
The JSON data that is now returned from the server is a single quote, as in the first example, and cannot be used directly. What about it?
The answer is the eval () function mentioned at the beginning.
Java code
<script>
var json='{"id":1}';
var jsonObj=eval("("+json+")");//注意这一行
alert(jsonObj.id);
</script>
The ID is displayed successfully.
Note two key points:
1. If JSON is just a single object, rather than an array of objects, as shown in the previous example, you cannot write Eval directly (JSON).
2. Eval ("+json+") cannot be written as an eval (' ("+json+ ') '), otherwise the ID will not be displayed.
Let me cite one more example:
Java code
<script>
var json='[{"id":1}]';
var jsonObj=eval(json);
alert(jsonObj[0].id);
</script>
IDs can still be displayed successfully. Note The difference: JSON contains an array of objects, not a single object. But why this can be, and the previous example is not possible, I was confused, but also asked the master enlighten.