我正在尝试将JSON数据渲染为HTML,如下所示:
var data = [
{"id":"856","name":"India"},
{"id":"1035","name":"Chennai"},
{"id":"1048","name":"Delhi"},
{"id":"1113","name":"Lucknow"},
{"id":"1114","name":"Bangalore"},
{"id":"1115","name":"Ahmedabad"},
{"id":"1116","name":"Cochin"},
{"id":"1117","name":"London"},
{"id":"1118","name":"New York"},
{"id":"1119","name":"California"}
];
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#myDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
}
&#13;
<table id="myDataTable">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</table>
&#13;
但它没有用。
答案 0 :(得分:0)
您没有调用您的函数drawTable()
。您也可以使用$.each()
来循环data
数组
var data = [{
"id": "856",
"name": "India"
}, {
"id": "1035",
"name": "Chennai"
}, {
"id": "1048",
"name": "Delhi"
}, {
"id": "1113",
"name": "Lucknow"
}, {
"id": "1114",
"name": "Bangalore"
}, {
"id": "1115",
"name": "Ahmedabad"
}, {
"id": "1116",
"name": "Cochin"
}, {
"id": "1117",
"name": "London"
}, {
"id": "1118",
"name": "New York"
}, {
"id": "1119",
"name": "California"
}];
drawTable();
function drawTable() {
var table = $("#myDataTable");
$.each(data, function(index, rowData) {
table.append(
"<tr>"
+"<td>"+rowData.id+"</td>"
+"<td>"+rowData.name+"</td>"
+"</tr>"
);
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myDataTable">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</table>
&#13;
答案 1 :(得分:0)
var data = [{
"id": "856",
"name": "India"
}, {
"id": "1035",
"name": "Chennai"
}, {
"id": "1048",
"name": "Delhi"
}, {
"id": "1113",
"name": "Lucknow"
}, {
"id": "1114",
"name": "Bangalore"
}, {
"id": "1115",
"name": "Ahmedabad"
}, {
"id": "1116",
"name": "Cochin"
}, {
"id": "1117",
"name": "London"
}, {
"id": "1118",
"name": "New York"
}, {
"id": "1119",
"name": "California"
}];
function drawRow(rowData) {
var table = document.getElementById('myDataTable');
for (var i = 0; i < rowData.length; i++) {
var tr = document.createElement('tr');
var td_1 = document.createElement('td');
var td_2 = document.createElement('td');
td_1.innerText = rowData[i].id;
td_2.innerText = rowData[i].name;
tr.appendChild(td_1);
tr.appendChild(td_2);
table.appendChild(tr);
}
}
drawRow(data);
&#13;
<table id="myDataTable">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</table>
&#13;