Javascript似乎无法从JSON构建HTML表

时间:2018-12-07 10:51:57

标签: javascript jquery json ajax

有没有一种方法可以加快以下javascript从json构建html表的速度?以下代码返回约1000行和10列的json,但是构建html表大约需要10秒钟。

我尝试先隐藏元素,以使用document.getElementById("data-tableResults").style.display = "none";来查看它是否是渲染问题,但是花费的时间相同。

Javacript不是我的母语,但是这似乎太慢了?

Ajax发布请求:

        currentRequest = $.ajax({
            type: 'POST',
            url: "../DataBuilder/Index",
            data: JSON.stringify({ dataObj: getData() }),
            success: function (returnPayload) {

                tableResults = returnPayload["data"];

                // Slow from here
                // document.getElementById("data-tableResults").style.display = "none";
                buildTableResults();
                // document.getElementById("data-tableResults").style.display = "block";
                console && console.log("request succeeded");

            },
            error: function (xhr, ajaxOptions, thrownError) {

                console && console.log("request failed");


            },
            dataType: "json",
            contentType: "application/json",
            processData: false,
            async: true
        });

建立表格功能<-这非常慢

    buildTableResults = function() {
        var tbody = $('#data-tableResults tbody'),
            props = ["field1", "field2", "field3", "field4", "field5", "field6", "field7", "field8", "field9", "field10"];
        tbody.empty();
        $.each(tableResults, function(i, reservation) {
            var tr = $('<tr>');
            $.each(props, function(i, prop) {
                $('<td>').html(reservation[prop]).appendTo(tr);
            });
            tbody.append(tr);
        });
    };

编辑:

我也尝试过在DOM之外构造表,然后替换它,但是我无法使它正常工作。

    buildTableResults = function () {
        var table = $('<table>', { id: 'data-tableResults' })
        var tbody = table.children('tbody'),
            props = ["field1", "field2", "field3", "field4", "field5", "field6", "field7", "field8", "field9", "field10"];
        tbody.empty();
        $.each(tableResults, function(i, reservation) {
            var tr = $('<tr>');
            $.each(props, function(i, prop) {
                $('<td>').html(reservation[prop]).appendTo(tr);
            });
            tbody.append(tr);
        });

        $('#data-tableResults').replaceWith(table);
    };

0 个答案:

没有答案