Before I have been not particularly familiar with Ajax, so generally rarely use this to write function, but recently used in this project, using AJAX asynchronous data transfer, JSON data will need to parse the data sent over, eval () and $.parsejson () Can parse the data, but they are also different;
1: Security
Cases:
var str = ' alert (1000.toString ()) ';
eval (str);
Json.parse (str);
You can parse it with eval, and the dialog box pops up, and the Json.parse () will not parse it. In fact, there is no harm to alert, it is scary to use a malicious user in the JSON string injected into the page to insert the Trojan link script, with Eval is also operable, and with Json.parse () do not have to worry about this problem.
Note: Some low-level browsers do not yet support Json.parse ()
2:json.parse () parsing must be a JSON-formatted string without error, and eval () is not so strict
Here "JSON-formatted string" means that the specified string must conform to a strict JSON format, for example: attribute names must be double-quoted, string values must also be double-quoted.
If you pass in a JSON string that is not well-formed, a JS exception will be thrown
There are two ways to parse JSON: eval and Json.parse (), such as:
var jsonstr= ' {' name ': ' Lulu ', ' sex ': ' Female '} ';
var evaljson=eval ('(' +jsonstr+') ');
var jsonparsejson=json.parse (JSONSTR);
This converts the JSON-formatted string JSONSTR to a JSON object.
But the difference is:
var age = 27;
var jsonstr= ' {' name ': ' Lulu ', ' sex ': ' Female ', ' age ': ++age} ';
From the use of the Eval () function above, we can see that the eval () function is to parse a JSON-formatted string with parentheses such as Eval (' (' +jsonstr+ ') '), because:
The question of Eval itself. Since JSON starts and ends in the form of "{}", in JS, it is treated as a block of statements, so it must be coerced into an expression.
The purpose of the parentheses is to force the Eval function to force the expression in parentheses to be converted to an object while processing the JavaScript code, rather than being executed as a statement (statement). For example, if the object literal {} is not enclosed, then eval will recognize the curly brace as the start and end tag of the JavaScript block, and {} will be considered an empty statement.
var evaljson=eval ('(' +jsonstr+') '); //No error when the value of age is
var jsonparsejson=json.parse (JSONSTR); //Error
The difference between eval () and $.parsejson () in JS