使用JavaScript动态更新表 [英] Dynamically update a table using javascript
问题描述
我在那里我发送一个Ajax请求到服务器的页面。有,它显示一些数据在页面上的表。服务器返回一个JSON对象,它是一个对象的列表,并将其不包含的页中的任何布局
I have a page where I send an ajax request to a server. There is a table on the page which displays some data. The server returns a json object which is a list of objects and it doesn't contain any layout for the page.
我想只更新表中的行按返回的JSON。我怎样才能做到这一点,而无需使用第三方库,只使用jquery?我只是希望有一个大概的了解和榜样。
I want to update only table rows by returned json. How can I do this without using third-party libraries and only using jquery? I just want a rough idea and example.
推荐答案
下面是 演示小提琴 。 (简版)
新:查看 更新小提琴 (高级版)。的
Here is the demo fiddle. (simple version)
NEW: See the updated fiddle (advanced version).
比方说,你有这样的JSON数据检索:
Let's say you have this JSON data retrieved:
var jsonData = [
{ field1: 'value a1', field2: 'value a2', field3: 'value a3', field4: 'value a4' },
{ field1: 'value b1', field2: 'value b2', field3: 'value b3', field4: 'value b4' },
{ field1: 'value c1', field2: 'value c2', field3: 'value c3', field4: 'value c4' }
];
和你有这个表:
<table id="data-table">
<tr><td>There are no items...</td></tr>
</table>
现在,您需要一个可以在自定义的顺序和presence解析值的方法。例如,如果你可以通过现场阵列分析器功能;您可以设置字段的顺序,如果你想留出一两个领域:
Now, you need a method that can parse the values in a customisable order and presence. For example, if you can pass a field array to the parser function; you can set the order of the fields and leave out a field or two if you want to:
loadTable('data-table', ['field1', 'field2', 'field3'], jsonData);
注意 FIELD4
未解析。
在可装入
函数遍历返回数组的项目,并创建一个&LT; TR&GT;
每个字段值在&LT; TD&GT;
。下面是简单的函数:
The loadTable
function loops through the items of the returned array and create a <tr>
with each field value inside a <td>
. Here is the simple function:
function loadTable(tableId, fields, data) {
//$('#' + tableId).empty(); //not really necessary
var rows = '';
$.each(data, function(index, item) {
var row = '<tr>';
$.each(fields, function(index, field) {
row += '<td>' + item[field+''] + '</td>';
});
rows += row + '<tr>';
});
$('#' + tableId).html(rows);
}
更新:
增加了支持:
UPDATE:
Added support for:
- 表头
- 在默认文本(空单)
- 追加名单
- 在收拾桌子
- 等等...
您现在可以简单地包括一个空表和 dynamicTable
将负责其余的:
You can now simply include an empty table and the dynamicTable
will take care of the rest:
<table id="data-table"></table>
致电 dynamicTable.config()
方法配置表:
var dt = dynamicTable.config('data-table', //id of the table
['field2', 'field1', 'field3'], //field names
['header 1', 'header 2', 'header 3'], //set to null for field names to be used as header names instead of custom headers
'There are no items to list...'); //default text for no items
然后调用 dt.load(数据);
来加载新数据(删除previous列表中,如果有一个),
或致电 dt.load(数据,真);
在previous列表的末尾追加新的数据。
Then call dt.load(data);
to load new data (removes the previous list if there is one),
OR call dt.load(data, true);
to append the new data at the end of the previous list.
调用 dt.clear();
方法清除整个列表
更新在这里捣鼓 。
这篇关于使用JavaScript动态更新表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!