Jquery parses the JSON data sample code

  • 2020-03-30 02:23:13
  • OfStack

Here you can find the json.js code, and then you need the formutil.js code and md5.js

The method of parsing JSON data with jquery is used as the transmission object of jquery asynchronous request. The result returned by jquery after the request is JSON object. Here, we consider the form of string returned by the server in JSON form.
The JSON string set is first shown here, and the string set is as follows:
The code is as follows:
 
var data=" 
{ 
root: 
[ 
{name:'1',value:'0'}, 
{name:'6101',value:' The Beijing municipal '}, 
{name:'6102',value:' tianjin '}, 
{name:'6103',value:' Shanghai '}, 
{name:'6104',value:' chongqing '}, 
{name:'6105',value:' weinan '}, 
{name:'6106',value:' Yan 'an '}, 
{name:'6107',value:' Grassland, '}, 
{name:'6108',value:' Yulin city '}, 
{name:'6109',value:' Ankang municipality '}, 
{name:'6110',value:' shangluo '} 
] 
}"; 

Based on the data types obtained asynchronously by jquery -- json objects and strings, this paper introduces the result processing methods obtained in two ways.
1. If the JSON string returned by the server is not typed or accepted as a string by the jquery asynchronous request, it needs to be objectized once, either by placing the string in eval() and executing it once. This method is also suitable for the common javascript method to obtain json objects, the following examples:
 
var dataObj=eval("("+data+")");//Convert to a json object
alert(dataObj.root.length);//Output the number of child objects of root
$.each(dataObj.root,fucntion(idx,item){ 
if(idx==0){ 
return true; 
} 
//Output the name and value of each root child object
alert("name:"+item.name+",value:"+item.value); 
}) 

Note: for a normal js generated json object, just replace the $.each() method with a for statement, and the rest remains the same.
2. For the server returns a JSON string, if the jquery asynchronous request will type (generally) for this configuration attribute set to "JSON", or use $. GetJSON () method to obtain the server returns, so there is no need for the eval () method, because this time the result is a JSON object, simply call the object can be directly, here to $. GetJSON method for example data processing methods:
 
$.getJSON("http://www.phpzixue.cn/",{param:"gaoyusi"},function(data){ 
//The data returned here is already a json object
//The following other operations are the same as the first case
$.each(data.root,function(idx,item){ 
if(idx==0){ 
return true;//Countinue returns false as a break
} 
alert("name:"+item.name+",value:"+item.value); 
}); 
}); 

It is important to note that the eval() method in approach 1 executes the string (possibly a js script) dynamically, which can easily cause security problems for the system. So you can use third-party client-side scripting libraries that circumvent eval(), such as JSON in JavaScript, which provides a script library of up to 3k.

Related articles: