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.
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); });
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.
The parameter is not being deprecated, the success method is. You can continue using success: function re-read it carefully.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With