简体   繁体   中英

How to handle my JSON data in jQuery Ajax success callback?

If I have a ajax call:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: function(json_data){
    //What's the efficient way to extract the JSON data and get the value
  }
});

Server returned to my js the following JSON data

{"contact":[{"address":[{"city":"Shanghai","street":"Long
            Hua Street"},{"city":"Shanghai","street":"Dong Quan
            Street"}],"id":"huangyim","name":"Huang Yi Ming"}]}

In my jQuery AJAX success callback function, how to extract the value of " name ", value of " address " (which is a list of object ) elegantly?

I am not experienced with jQuery and JSON data handling in javascript. So, I would like to ask some suggestions on how to handle this data efficiently. Thanks.

A JSON string gets parsed into a JavaScript object/array. So you can access the values like you access any object property, array element:

var name = json_data.contact[0].name;
var addresses = json_data.contact[0].address;

Do access the values inside each address, you can iterate over the array:

for(var i = addresses.length; i--;) {
    var address = addresses[i];
    // address.city
    // address.street
    // etc
}

If you have not so much experience with JavaScript, I suggest to read this guide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM