根据JSON填写html表格 [英] Fill html table based on JSON
问题描述
我需要将调用URL的结果映射到html表中,但我找不到一种方法来完成它。
I need to map the result of calling an URL into html table but I can't figure out a way to do it.
要用于的URL获取数据是 https://abcdefghi/h5s5-hcxg.json 。那么任何人都可以帮助我如何从这个URL中获取数据?
The URL to be used to get data is "https://abcdefghi/h5s5-hcxg.json". So can anyone help me with how to get data into tables from this URL ?
请参阅我的代码:
See my code bellow:
<script>
$.ajax({
url: "https://abcdefghij.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
for (var i=0;i<json.length;++i)
{
$('#results').append('<div class="name">'+json[i].name+'</>');
}
}
});
</Script>
推荐答案
您没有正确引用json对象。 json [i] .name应该是你之后的关键字,例如json [i] .total_capacity_certified,因为json文件中没有名称键,结果将显示为空。下面的代码循环遍历每个json对象,并为每个键创建一个新的表列
You're not reference the json object correctly. json[i].name should really be the key you're after eg json[i].total_capacity_certified, because there is no name key in the json file your result will appear empty. The code below loops through each json object and for every key creates a new table column
<table id="results">
<tr>
<td></td>
</tr>
</table>
.js
$.ajax({
url: "https://health.data.ny.gov/resource/h5s5-hcxg.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
// we'll put all our html in here for now
var html = '';
for (var i=0;i<json.length;++i)
{
// if on first loop, create the col headers
if(i===0){
html += '<thead><tr>';
$.each(json[i], function(key, value){
html += '<td>'+key+'</td>' ;
});
html += '</thead></tr>';
}
// loop through all the json objects and for every key add a column with the value
html += '<tr>';
$.each(json[i], function(key, value){
html += '<td>'+value+'</td>' ;
});
html += '</tr>';
}
// push all the html in one go to the page
$('#results').append(html);
}
});
这篇关于根据JSON填写html表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!