user1647234 user1647234 - 2 months ago 10
JSON Question

Populate span tag with data from a json file

On THIS page, I have listed some dummy estates and hard-coded, for each one, a span (with the text "VEZI TELEFON") that when clicked, reveals a phone number. I want every phone number to be retrieved from a JSON (or PHP) file called telefoane.json that has the content:

{
"telefoane":[{
"id":"1",
"tel":"0743127315"
},
{
"id":"2",
"tel":"072245875"
},
{
"id":"3",
"tel":"0756129458"
},
{
"id":"4",
"tel":"0725127216"
},
{
"id":"5",
"tel":"0723127322"
}]
}


My code, that can be seen below does not output the desired result:

$.ajax({
url: 'telefoane.json',
dataType: 'json',
success: function(data){
$.each(data, function(key, val){
console.log(key + ":" + val);
});
}
});


The output is, unfortunately:

telefoane:[object Object],[object Object],[object Object],[object Object],[object Object]


What am I doing wrong? Thank you!

EDIT:

$.ajax({
url: 'telefoane.json',
dataType: 'json',
success: function(){
$.each(data.telefoane, function() {
console.log(this.id + ": " + this.tel);
});
}
});

Answer

Your loop will give you the objects of data.telefoane. So you need to access the content by the property names.

var data = {
  "telefoane": [
  {
    "id": "1",
    "tel": "0743127315"
  }, {
    "id": "2",
    "tel": "072245875"
  }, {
    "id": "3",
    "tel": "0756129458"
  }]
};

$.each(data.telefoane, function(i, object) {
  console.log(object.id + ": " + object.tel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or use this:

var data = {
  "telefoane": [
  {
    "id": "1",
    "tel": "0743127315"
  }, {
    "id": "2",
    "tel": "072245875"
  }, {
    "id": "3",
    "tel": "0756129458"
  }]
};

$.each(data.telefoane, function() {
  console.log(this.id + ": " + this.tel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>