Json data is a commonly used small data exchange in real time. It can be parsed using jquery or js. Next, I will introduce the jquery method of parsing json strings.
1. jQuery parses Json data format:
Using this method, you must set parameters in the Ajax request:
1 dataType: "json"
Get through the callback function Return the data and parse it to get the value we want. See the source code:
jQuery.ajax({
url: full_url,
dataType: "json",
success: function(results) {
alert(result.name);
} }) ;
Normally, you can return JSON data from the background, and leave the frontend to jQuery, haha! !
Jquery asynchronous request sets the type (usually this configuration attribute) to "json", or uses the $.getJSON() method to obtain the server return, then there is no need
eval() method, because at this time you get The result is already a json object. You only need to call the object directly. Here, the $.getJSON method is used as an example.
Example 1
The code is as follows:
var data="
{
root:
[
{name :'1',value:'0'},
{name:'6101',value:'Beijing'},
{name:'6102',value:'Tianjin'},
{name:'6103',value:'Shanghai City'},
{name:'6104',value:'Chongqing City'},
{name:'6105',value:'Weinan City' },
{name:'6106',value:'Yan'an City'},
{name:'6107',value:'Hanzhong City'},
{name:'6108',value: 'Yulin City'},
{name:'6109',value:'Ankang City'},
{name:'6110',value:'Shangluo City'}
]
}" ;
jquery
$ .getJSON("http://sanic.cnblogs.com/",{param:"sanic"},function(data){
//The data returned here is already a json object
//Others below The operation is the same as the first case
$.each(data.root,function(idx,item){
if(idx==0){
return true;//Same as countinue, return false the same as break
}
alert("name:" item.name ",value:" item.value);
});
});
2. jQuery parses Json objects:
jQuery provides another method "parseJSON", which requires a standard JSON string and returns the generated JavaScript object. Let’s look at
and see the syntax:
data = $.parseJSON(string);
and see how it is used in actual development:
jQuery.ajax({
url: dataURL, success: function(results) {
var parsedJson = jQuery.parseJSON(results);
alert(parsedJson.name);
}
});