2017-01-04 7 views
-1

Так что я в настоящее время есть таблица, которую я знаю, как заполнить с помощью How to load JSON data into Bootstrap table?Загрузка JSON в таблицу без Bootstrap-таблицы

Мой вопрос более любопытство основе. Можно ли загружать данные JSON в таблицу, загруженную в Bootstrap, без использования библиотеки bootstrap-table?

+0

Вы имеете в виду, чтобы сформировать регулярную HTML таблицу с данными JSON, а затем преобразовать его в таблицу Bootstrap? Вы можете создать плагин jQuery. –

ответ

1

Ответ да. Вы можете редактировать все HTML с помощью JS, поэтому, пока вы пишете правильный скрипт, вы сможете десериализовать JSON и заполнить таблицу.

1

Что вам нужно, это просто шаблон, который может работать с данными json для генерации Структура html dom, например, загрузочная таблица.

Использование ExtJS XTemplate в качестве примера:

// this is a template 
var tableTemplate = new Ext.XTemplate(
    '<table class="table {tableClass}">', 
    '<thead>', 
     '<tr>', 
     '<tpl for="columns">', 
      '<th>{name}</th>', 
     '</tpl>' 
     '</tr>', 
    '</thead>', 
    '<tbody>', 
     '<tpl for="row in rows">', 
     '<tr>', 
      '<tpl for="column in columns">', 
      '<td>{row[column]}</td>', 
      '</tpl>' 
     '</tr>', 
     '</tpl>', 
    '</tbody>', 
    '</table>' 
); 

// this is the data load from end-server 
var data = { 
    columns: [{ 
     name: 'a' 
    }, { 
     name: 'b' 
    }, { 
     name: 'c' 
    }], 
    rows: [{ 
     a: 'a1', 
     b: 'b1', 
     c: 'c1' 
    }, { 
     a: 'a2', 
     b: 'b2', 
     c: 'c2' 
    }, { 
     a: 'a3', 
     b: 'b3', 
     c: 'c3' 
    }] 
}; 

//generate html with template and data 
tableTemplate.overwrite(dom, data); 
1

Это простой; расширяемый плагин jQuery, который я взбивал, который можно легко модифицировать.

Вам просто нужно передать объект в columns и records данных.

Я сохранил образец JSON в невидимой TextArea и просто извлек и проанализировал данные перед отправкой его в функцию плагина.

(function($) { 
 
    $.fn.populateTable = function(tableData) { 
 
    $('<thead>').append($('<tr>').append(tableData.columns.map(function(column) { 
 
     var colIsObj = column !== null && typeof column === 'object'; 
 
     var dataIndex = colIsObj ? column.fieldName : column; 
 
     var displayText = colIsObj && column.text != '' ? column.text : dataIndex; 
 
     return $('<th>').text(displayText); 
 
    }))).appendTo(this); 
 
    $('<tbody>').append(tableData.records.map(function(record) { 
 
     return $('<tr>').append(tableData.columns.map(function(column) { 
 
     var colIsObj = column !== null && typeof column === 'object'; 
 
     var dataIndex = colIsObj ? column.dataIndex : column; 
 
     var value = colIsObj && column['convert'] != null ? column.convert(record) : record[dataIndex]; 
 
     return $('<td>').text(value).css(colIsObj ? (column.css || {}) : {}); 
 
     })); 
 
    })).appendTo(this); 
 
    return this; 
 
    }; 
 
})(jQuery); 
 

 
var tableData = { 
 
    "columns" : [ 
 
    "id", 
 
    { 
 
     //"dataIndex" : "name", <-- Optional if text is defined. 
 
     "text" : "Full Name", 
 
     "convert" : function(record) { 
 
     return record.givenName + " " + record.surname; 
 
     } 
 
    }, { 
 
     "dataIndex" : "dob", 
 
     "text" : "Date of Birth", 
 
     "convert" : function(record) { 
 
     return moment(record.dob).format('MMMM Do, YYYY'); 
 
     }, 
 
     "css" : { 
 
     "text-align" : "center" 
 
     } 
 
    } 
 
    ], 
 
    "records" : JSON.parse(document.getElementById('json-data').innerHTML) 
 
}; 
 

 
$('#data-table').populateTable(tableData);
#json-data { display: none; } 
 
#data-table, #data-table th, #data-table td { border-collapse: collapse; border: thin solid black; } 
 
#data-table th, #data-table td { padding: 0.25em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> 
 

 
<textarea id="json-data">[ { 
 
    "id" : 1, 
 
    "givenName" : "John", 
 
    "surname" : "Doe", 
 
    "dob" : "1950-12-31" 
 
    }, { 
 
    "id" : 2, 
 
    "givenName" : "Jane", 
 
    "surname" : "Doe", 
 
    "dob" : "1968-07-04" 
 
} ]</textarea> 
 
<table id="data-table"></table>

Смежные вопросы