下面的代碼是我從API接收到的JSON響應。不幸的是我不能改變這個響應的發送方式,我只能在Javascript/jQuery的範圍內使用這個響應。將數組轉換爲HTML表的JSON對象
我的目標是將其轉換爲HTML表格。
我已經試圖自己做這件事了;
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table id="res" class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index.toUpperCase() + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt" id="' + array[i]['id'] + '">' : '<tr id="' + array[i]['id'] + '">';
for (var index in array[i]) {
str += '<td style="width:15%;">' + htmlspecialchars_decode(array[i][index]) + '</td>';
}
str += '<td><a href="#" onClick="editPerson(' + array[i]['id'] + ');">Edit</a></td><td><a href="#" onClick="delPerson(' + array[i]['id'] + ');">Delete</a></td></tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
但是我只能得到頭以示...但它工作得很好,如果JSON響應只有一個陣列,即一行返回。
以上是從#2這樣的幾個其他問題改編的代碼,我花了幾天就這個問題和不能得到這些結果以表格顯示......這是很多其他的只是一個例子被就跟返回這個例子,我將需要多次重用這個解決方案,這對我來說非常重要。
"ItemArray":{
"id":"14"
,"0":
{"id":"1","username":"guest","fname":"Guest","lname":"User","email":"[email protected]","group":"member","active":"0","url":null,"last_activity":null}
,"1":
{"id":"2","username":"system","fname":"Internal","lname":"System","email":"[email protected]","group":"member","active":"0","url":null,"last_activity":null}
,"2":
{"id":"3","username":"master","fname":"Super","lname":"Admin","email":"[email protected]","group":"member","active":"0","url":null,"last_activity":null}
,"3":
{"id":"14","username":"apitest","fname":"API","lname":"Test","email":"[email protected]","group":"member","active":"0","url":null,"last_activity":"2012-10-29 02:48:43"}
}
你得到了JSON的例子嗎? –