使用json文件中的数据填充span标记

时间:2016-09-27 10:54:13

标签: jquery json ajax

THIS页面上,我列出了一些虚拟庄园,并为每一个版本添加了一个跨度(带有文字" VEZI TELEFON"),当点击时,会显示一个电话号码。我希望从名为 telefoane.json 的JSON(或PHP)文件中检索每个电话号码,该文件包含以下内容:

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

我的代码,如下所示,无法输出所需的结果:

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

不幸的是,输出是:

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

我做错了什么?谢谢!

编辑:

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

1 个答案:

答案 0 :(得分:2)

你的循环会给你data.telefoane的对象。因此,您需要通过属性名称访问内容。



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>
&#13;
&#13;
&#13;

或使用this

&#13;
&#13;
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);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;