Javascript: How To Loop Through Json Objects With Jquery In An Ajax Call
I am having difficulty trying to learn this concept. I have a JSON file with a list of hospitals, their address, hours and phone. I want to make an AJAX call from JSON data and li
Solution 1:
Here's a working example:
var url = 'https://api.myjson.com/bins/b29r7';
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
// JSON data arrayvar data = result.surrey;
// get DOM node to be parent of child list nodesvar $data = $('#data');
// iterate through each object in JSON array
data.forEach(function(item) {
// create an unordered list nodevar $ul = $('<ul></ul>');
// iterate through all the properties of current JSON objectfor (var field in item) {
// append list item node to list node
$ul.append(`<li>${field}: ${item[field]}</li>`);
}
// append list node to parent node
$data.append($ul);
});
}).fail(function(error) {
console.error(error);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="data"></div>
JSFiddle Demo: https://jsfiddle.net/L6j8n17j/4/
Solution 2:
UPDATE : This is more clear version. You can print your values in your html like this.
$.ajax({
type: 'ajax',
url: 'https://api.myjson.com/bins/b29r7',
async: false,
dataType: 'json',
success: function (data) {
data = data.surrey;
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html+='<span>'+data[i].hospital+'</span>';
html+='<span>'+data[i].address+'</span>';
//so on
}
$('#data').html(html);
},
error: function () {
alert('Could not get Data');
}
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass='data'></div>
This should bring your values on the console and then you can use html function at the same time in the loop to display the data. Thanks!
Solution 3:
as per requirement please try below code
var url = 'https://api.myjson.com/bins/b29r7';
$.ajax({
url: url,
method: 'GET',
}).done(function(result){
var data = result.surrey;
var i = 0;
var hosData = "<table border='1'>";
hosData += "<tr>";
hosData += "<th>";
hosData += 'hospital';
hosData += "</th>";
hosData += "<th>";
hosData += 'address';
hosData += "</th>";
hosData += "<th>";
hosData += 'hours';
hosData += "</th>";
hosData += "<th>";
hosData += 'phone';
hosData += "</th>";
hosData += "</tr>";
for(i=0;i<data.length;i++)
{
hosData += "<tr>";
hosData += "<td>";
hosData += data[i].hospital;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].address;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].hours;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].phone;
hosData += "</td>";
hosData += "</tr>";
}
hosData += "</table>";
$("#data").html(hosData);
}).fail(function(err){
throw err;
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="data"></div>
Post a Comment for "Javascript: How To Loop Through Json Objects With Jquery In An Ajax Call"