在JavaScript中使用JSON的数据动态填充表的快速方法 [英] Fast way to dynamically fill table with data from JSON in JavaScript

查看:104
本文介绍了在JavaScript中使用JSON的数据动态填充表的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery,JSON等,并且遇到了以下任务。我在服务器上有一个加载器脚本,以JSON格式返回表数据。收到JSON数据时,我想填写我们的表。我目前使用的代码类似于以下(有更多的列和一些更高级的处理,但你得到的想法):

I am experimenting with jQuery, JSON etc. and came across following task. I have a loader script on the server which returns table data in JSON format. When received the JSON data, I want to fill my table with them. I am currently using code similar to following (there are more columns and some more advanced processing, but you got the idea):

...
for (var key=0, size=data.length; key<size;key++) {

  $('<tr>')
            .append( $('<td>').html(
                data[key][0]
            ) )
            .append( $('<td>').addClass('whatever1').html(
                data[key][1]
            ) )
            .append( $('<td>').addClass('whatever2').html(
                data[key][2]
            ) )
            .appendTo('#dataTable');
}
...

<table id="#dataTable"></table>
...

这几乎可以。但是一旦数据不断增长,就会变得非常慢。对于很少的纪录记录,它需要大约5秒(Firefox,IE)来构建表格,这有点慢。如果我在服务器上创建整个HTML,并将其作为字符串发送到表中,这将是非常快的。

This works pretty much ok. But once the data is growing it's getting terribly slow. For few hunderts of records it take up to about 5s (Firefox, IE) to build the table and that is a bit slow. If I e.g. create the whole HTML on the server and send it as string which I include in the table it will be pretty fast.

那么,有更快的方式填写表吗?

So, is there faster way to fill the table?

注意:我知道什么是分页,我最终会使用它,所以请不要说你需要什么你的页面上的大桌子?这个问题是关于如何快速填写表,无论你将显示多少条记录:)

NOTE: I know what is paging and I will use it in the end so please don't say "What do you need such a big table on your page for?". This question is about how to fill table quickly no matter how many records you will display :)

推荐答案

请参阅我的回复使用数组和加入。

See my response to an earlier similar query using arrays and "join".

直到最后,不要使用jQuery,只要调用一次即可。另外,也可以通过将字符串存储在数组中并使用join方法一次性创建字符串来切出字符串连接。

Don't use jQuery at all until the very end, when you call it just once. Also, cut out string concatenation as well by storing the strings in an array and using the "join" method to build the string in one go.

eg

 var r = new Array(), j = -1;
 for (var key=0, size=data.length; key<size; key++){
     r[++j] ='<tr><td>';
     r[++j] = data[key][0];
     r[++j] = '</td><td class="whatever1">';
     r[++j] = data[key][1];
     r[++j] = '</td><td class="whatever2">';
     r[++j] = data[key][2];
     r[++j] = '</td></tr>';
 }
 $('#dataTable').html(r.join('')); 

这篇关于在JavaScript中使用JSON的数据动态填充表的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆