sábado, 16 de junio de 2012

Mostrando objeto JSON en tabla HTML


Permite crear una tabla standard con filas y columnas desde un objeto JSON.Se importaron las siguientes librerías de proyecto.
<script src="scripts/json.htmTable.js">
</script>
<link rel="stylesheet" href="css/default.css">

 Se utiliza la función CreateTableView?? utilizando 3 parámetros:objArray = Objeto array tipo JSONTheme (Opcional) = nombre del theme o estilo a elecciónHeader (Opcional) = True si se quiere mostrar la cabecera de la tabla.

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 class="' + theme + '">';
 
    // table head
    if (enableHeader) {
        str += '<thead><tr>';
        for (var index in array[0]) {
            str += '<th scope="col">' + index + '</th>';
        }
        str += '</tr></thead>';
    }
 
    // table body
    str += '<tbody>';
    for (var i = 0; i < array.length; i++) {
        str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
        for (var index in array[i]) {
            str += '<td>' + array[i][index] + '</td>';
        }
        str += '</tr>';
    }
    str += '</tbody>'
    str += '</table>';
    return str;
}

1 comentario: