Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 840
Mellon Avatar asked Apr 14 '11 10:04

Mellon


People also ask

How do I return data after AJAX call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

How do I get AJAX response in JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

Is AJAX successful deprecated?

The parameter is not being deprecated, the success method is. You can continue using success: function re-read it carefully.

How do I know if AJAX request is successful?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.


1 Answers

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.

like image 66
Felix Kling Avatar answered Oct 09 '22 20:10

Felix Kling