我很新入jQuery和JSON。我需要解析以下格式的JSON,以便填充HTML表格的tbody:如何將json數組數據添加到html表tbody
{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}
但我不知道如何訪問它們,因此要獲得HTML表格以下列方式:
header1 header2 header3
name0 id0 amt0
name1 id1 amt1
我很新入jQuery和JSON。我需要解析以下格式的JSON,以便填充HTML表格的tbody:如何將json數組數據添加到html表tbody
{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}
但我不知道如何訪問它們,因此要獲得HTML表格以下列方式:
header1 header2 header3
name0 id0 amt0
name1 id1 amt1
未經測試,但它可以是這樣的:下面的HTML(例如,在文件準備好)後
var jsondata=$.parseJSON('{"response":[["name0","id0","amt0"],["name1","id1","amt1"]]}');
$.each(jsondata.response, function(i, d) {
var row='<tr>';
$.each(d, function(j, e) {
row+='<td>'+e+'</td>';
});
row+='</tr>';
$('#table tbody').append(row);
});
這是有效的。這裏是一個JSFiddle http://jsfiddle.net/JQk6Z/ –
非常感謝尼爾肯尼迪 –
感謝您的幫助MazarD! –
可以訪問JSON室內用結構此Javascript表達:
var matrix = {"response":[["name0","id0","amt0"],["name1","id1","amt1"]]};
第i個元素的第j列與此訪問:
matrix.response[i][j]
呼叫jsonToHtmlTable(jsonObj, '#records');
的Html
<table id="records">
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
的JavaScript
//Sample JSON Object (array of json objects)
var jsonObj = [{"a":1,"b":3,"ds":4},{"a":2,"b":5,"ds":4}];
//Use
$(document).ready(function(){
jsonToHtmlTable(jsonObj, '#records');
});
//implementation
function jsonToHtmlTable(jsonObj, selector) {
addColumns(jsonObj, selector);
addRows(jsonObj, selector);
}
function addColumns(jsonObj, selector) {
if (!$.isArray(jsonObj) || jsonObj.length < 1)
return;
var object = jsonObj[0];
var theadHtml = "";
for (var property in object) {
if (object.hasOwnProperty(property))
theadHtml += "<th>" + property + "</th>";
}
$(selector + ' thead tr').html(theadHtml);
}
function addRows() {
var tbody = $(selector + ' tbody');
$.each(jsonObj, function (i, d) {
var row = '<tr>';
$.each(d, function (j, e) {
row += '<td>' + e + '</td>';
});
row += '</tr>';
tbody.append(row);
});
}
你嘗試過什麼嗎? –