Home >Web Front-end >JS Tutorial >How jQuery parses Json string (Json format/Json object)_jquery

How jQuery parses Json string (Json format/Json object)_jquery

WBOY
WBOYOriginal
2016-05-16 17:26:061168browse

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:

Copy the code The code is as follows:

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:

Copy code 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

Copy code The code is as follows:
$ .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:

Copy code The code is as follows:
jQuery.ajax({
url: dataURL, success: function(results) {
var parsedJson = jQuery.parseJSON(results);
alert(parsedJson.name);
}
});

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn