Here to introduce you to the AJAX analysis of JSON two methods of comparison, very practical, this article for learning notes, is a novice article, welcome advice!
eval (); This method does not recommend
Json.parse (); Recommended methods
The difference of one or two methods
We first initialize an object in JSON format:
?
1 2 3 4 5 |
var jsondate = ' {' name ': ' Chow Chi ', ' Age ': '} ' var jsonobj = eval (' + jsondate + ') '; eval (); method var jsonobj = Json.parse (jsondate); Json.parse (); Method |
Then call on the console:
Console.log (Jsonobj.name); Both methods can correctly input Chow Chi
So what's the difference between the two methods? (Let's change the code slightly, the blue font is the modified part)
?
1 2 3 4 5 |
var jsondate = ' {' Name ': Alert ("Hello"), "Age":} ' var jsonobj = eval (' (' + jsondate + ') '); eval (); method Console.log (Jsonobj.age); The "alert" output "Hello" will be executed before the output is 23 |
Change "json.parse ();" Method:
?
1 2 3 4 5 |
var jsondate = ' {' Name ': Alert ("Hello"), "Age":} ' var jsonobj = Json.parse (jsondate); Json.parse (); Method Cosole.log (Jsonobj.age)//error message This tells us that this string is illegal. |
Summary: "eval ();" When parsing a method, it is very dangerous to not judge whether the string is legitimate, and the JS method in the JSON object is executed, and "Json.parse ()". The advantage of the method is needless to say, this method is recommended. (Do not understand the pot friends can test themselves in the console)
II. Expansion issues
The code is as follows:
var jsondate = ' {' name ': ' Chow Chi ', ' age ': 23} '
You can see that the quotation marks are marked in red at the time of the test, with the bag outside the curly braces. This pair of quotes is critical but often overlooked because "eval ();" and "Json.parser ();" The parameters of the two methods only accept strings, that is, only strings are parsed!!
Then I will not have a thought, when we initialize without the quotation mark, then it is the object, JS can directly get the object itself properties and methods; Why do I have to quote it into a string and then use "eval ();" or "json.parse ();" Parse, Is this not environmentally friendly and inefficient?
The reason is very simple: the front-end provided to the background can only be string data format, back to the foreground in the background to see what data format is returned, is the string must be resolved after the use.
(This small problem is generally overlooked, not too much attention.) I am curious because of the reason is not enough to understand the background, the problem is thrown out to hope that the background is not familiar with the friend to help, know how back to the natural will deepen the memory, in the development process will not be missed out.
The above mentioned is the entire content of this article, I hope you can enjoy.