2016-11-30 69 views
-2

在html中显示json信息的最佳方式是什么?我尝试了以下方法,但它似乎不起作用。在html中显示json数据

我的代码

$.getJSON('example.json', function(data) { 
 
     var html = ''; 
 
     $.each(data.example, function(key, value) { 
 

 
\t \t \t html += '<p> Name:' + value.name + '</p>'; 
 

 
\t \t \t html += '<p> Email:' + value.email + '</p>' 
 

 
       }); 
 

 
     $('#example').append(html); 
 
    }); 
 
});

我的JSON

{ 
 
    "example": [ 
 
     { 
 
      "name": "Dr. Sammie Boyer", 
 
      "email": "[email protected]" 
 
     }, 
 
     { 
 
      "name": "Eladio Beier", 
 
      "email": "[email protected]" 
 
     }, 
 
     { 
 
      "name": "Hilton Borer", 
 
      "email": "[email protected]" 
 
     } 
 
    ] 
 
}

+1

也许'$。每个(data.example' – Paolo

+0

如果你把'的console.log()'循环例如'的console.log(value.name)内;'或' console.log(value);'你在得到什么? – noodlesegg

+0

控制台打印从json文件中的所有内容,但它仍然不显示在html – Rebekah

回答

0

它总是有帮助的事情console.log你试试荷兰国际集团调试,如果你做一个console.logdata运行,你会看到,没有什么所谓的contacts,因为它被称为在JSON文件example,尝试改变无论是example - 在你的代码>example - >在JSON contactscontacts

+0

仍然不工作 – Rebekah

0

检查它可以帮助你。

var data = { 
 
    "example": [ 
 
     { 
 
      "name": "Dr. Sammie Boyer", 
 
      "email": "[email protected]" 
 
     }, 
 
     { 
 
      "name": "Eladio Beier", 
 
      "email": "[email protected]" 
 
     }, 
 
     { 
 
      "name": "Hilton Borer", 
 
      "email": "[email protected]" 
 
     } 
 
    ] 
 
}; 
 
     var html = ''; 
 
     $.each(data.example, function(key, value) { 
 

 
\t \t \t html += '<p> Name:' + value.name + '</p>'; 
 

 
\t \t \t html += '<p> Email:' + value.email + '</p>' 
 

 
       }); 
 

 
     $('#example').append(html); 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div id="example"> </div>