gpt4 book ai didi

jquery - 如何优化将大量元素动态添加到网页中

转载 作者:太空狗 更新时间:2023-10-29 15:09:44 25 4
gpt4 key购买 nike

我需要从我的数据库中检索许多记录并将它们显示给用户。我使用 ajax 执行此操作,并将应添加到页面的所有内容存储在单个字符串中。目前,我的加载时间有问题(每 100 条记录 1 秒)。例如,加载 1000 行需要 10 秒,而查询本身可以在不到 1 秒的时间内完全执行。这意味着瓶颈是创建元素并将它们添加到网页中。

//client side code    
$(document).ready(function () {
loadGrid(function () {
$(".rowCount").val($(".tbody .tr:visible").length);
});

function loadGrid(callback) {
$.ajax({
type: "POST", url: "Ledger.aspx/LoadGrid",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$(".tbody").html(response.d); //response.d = '<div class='tr'> <div class='td colIdVchItm'>1</div>...</div>'
callback();
},
failure: function (response) {
ShowMessage(response.d);
}
});
}

//server side code
[WebMethod]
public static string LoadGrid()
{
string q = @"select cast((select 'tr' as [@class],
'td colIdVchItm' as [div/@class] , a.IdVchItm as [div], ' ',
'td colNo' as [div/@class] , a.No as [div], ' ',
'td colRef' as [div/@class] ,a.Ref as [div], ' ',
'td colSeq' as [div/@class] ,a.Seq as [div], ' ',
'td colDescr' as [div/@class] ,a.Descr as [div], ' ',
'td colDebit' as [div/@class] , cast(a.Debit as decimal(38,0)) as [div], ' ',
'td colCredit' as [div/@class] , cast(a.Credit as decimal(38,0)) as [div], ' ',
'td colBalance' as [div/@class] ,null as [div] , ' ',
'td colCur' as [div/@class] ,b.Title as [div], ' ',
'td colCurVal' as [div/@class] ,a.CurVal as [div], ' ',
'td colEffDate' as [div/@class] ,dbo.ShamsiDate(a.EffectiveDate) as [div] , ' '
from a inner join Currency as b on a.IdCur = b.IdCur order by a.vchdate, a.no
for xml path('div')) as nvarchar(max))";
// this query returns every records as an html text. for example:
// <div class='tr'> <div class='td colIdVchItm'>1</div>...
string res = "";
SqlConnection con = new SqlConnection(DAL.conStr);
SqlCommand com = new SqlCommand(q, con);
con.Open();
SqlDataReader rd = com.ExecuteReader();
rd.Read();
res = rd[0].ToString();
con.Close();
return res;
}

如果你能帮助我优化这个过程,我将不胜感激。

最佳答案

@Bhenam: $(".tbody").html() 内部使用 innerHTML,这需要重建 DOM,但使用 append() jquery 方法将内容添加到该节点中的 child 。

你能试试下面的代码吗?

 success: function (response) {
$(".tbody").html('');
$(".tbody").append(response.d);

callback();
}

所有浏览器都支持。 https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

关于jquery - 如何优化将大量元素动态添加到网页中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56432714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com