In JS, the JSON string is parsed into a JSON data format, typically in two ways:
1. One for using the eval () function.
2. Use the function object for return parsing.
(i) The data types obtained asynchronously by jquery are based on the--json object and the string, and describe how the results are handled in two ways
1. For the JSON string returned by the server, if the jquery asynchronous request does not make a type description, or is accepted as a string, then an object processing is required, either in a cumbersome way or by placing the string in eval ().
var dataobj=eval ("(" +data+ ")");//Convert to JSON object
Why should Eval be added here ("(" +data+ ")")?
The reason is that eval itself is a problem. 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. So the following two execution results are different:
Alert (eval ("{}"); return undefined
Alert (eval ("({})");//return Object[object]
2. For the JSON string returned by the server, if the jquery asynchronous request sets the type (typically this configuration property) to "JSON", or uses the $.getjson () method to get the server back, then the eval () method is not required. Because the result is already a JSON object, just call the object directly, here $.getjson method as an example to illustrate the data processing method:
$.getjson ("http://www.phpzixue.cn/", {param: "Gaoyusi"},function (data) {
The data returned here is already a JSON object
The following other actions are the same as the first case
$.each (Data.root,function (Idx,item) {
if (idx==0) {
Return true;//with Countinue, returns false with break
}
Alert ("Name:" +item.name+ ", Value:" +item.value ");
});
});
(b) Parsing is done using a function object, and its typical application is the success of the Ajax method in jquery, and so on to return data
var json= ' {' name ': ' CJ ', ' Age ': 18} ';
data = (New Function ("", "Return" +json)) ();
Data in this case is parsed into a JSON object.
Ajax returns JSON processing