Display data in an HTML table using JavaScript/jQuery

会有一股神秘感。 提交于 2021-02-10 13:16:33

问题


I have a JSON response like the following.

"result": [
    [1, 0.10, 1.00],
    [2, 0.20, 2.00],
    [3, 0.30, 3.00],
    [4, 0.40, 4.00],
    [5, 0.50, 5.00],
    [6, 0.60, 6.00],
    [7, 0.70, 7.00],
    [8, 0.80, 8.00],
    [9, 0.90, 9.00],
    [10, 1.00, 10.00],
    [11, 1.10, 11.00],
    [12, 1.20, 12.00],
    [13, 1.30, 13.00],
    [14, 1.40, 14.00],
    [15, 1.50, 15.00],
    [16, 1.60, 16.00],
    [17, 1.70, 17.00],
    [18, 1.80, 18.00]
]

This corresponds to a java.util.List<Object[]> in Java.


The response is received by the following JavaScript/jQuery function.

var timeout;
var request;

$(function () {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});

$(document).ready(function(){
    $("#zoneCharge").change(function(){
        if(!request)
        {
            request = $.ajax({
                datatype:"json",
                type: "POST",
                data: JSON.stringify({jsonrpc:'2.0', method:'getZoneCharges', id:'jsonrpc', params:[$("#zoneCharge").val()]}),
                contentType: "application/json-rpc; charset=utf-8",
                url: "ZoneChargeList",
                success: function(response)
                {
                    var list=response.result;
                    var tempWeight='';
                    $('#dataTable').remove();
                    var $table = $("<table id='dataTable' cellpadding='0' cellspacing='0' width='100%'>").appendTo($('#zoneChargeList'));

                    $('<tr>').appendTo($table)
                    //.append($("<th style='width: 96px;'>").text("Weight"))
                    //.append($("<th style='width: 96px;'>").text("Charge"))
                    .append($("<th style='width: 96px;'>").text("Weight"))
                    .append($("<th style='width: 96px;'>").text("Charge"));

                    $.each(list, function(index, list) {
                        list[2]===null||list[2]===undefined||list[2]===''||isNaN(list[2])?tempWeight='':tempWeight=list[2].toFixed(2);
                        $('<tr>').appendTo($table)
                        .append($('<td>').text(list[1]))
                        .append($("<td><input type='text' name='txtCharge[]' value='"+tempWeight+"' onkeypress='return isNumberKey(event, this.value);'>"));

                    });
                },
                complete: function()
                {
                    timeout = request = null;
                },
                error: function(request, status, error)
                {
                    if(status!=="timeout"&&status!=="abort")
                    {
                        alert(status+" : "+error);
                    }
                }
            });
            timeout = setTimeout(function() {
                if(request)
                {
                    request.abort();
                    alert("The request has been timed out.");
                }
            }, 30000);
        }
    });
});

<span id="zoneChargeList"></span>

I want to display this list of data in <table> in the following format.

enter image description here


The $.each function in the success handler currently displays this list in <table> in the following format.

enter image description here

How to show this list in a table of four columns as shown by an equivalent snap shot above?

The jQuery function is invoked when an item is selected from <select> whose id is zoneCharge


回答1:


Something like this should work (and here's a fiddle to demonstrate: http://jsfiddle.net/83d4w/5/) :

var newTr = null;
var resetTr = true;
$.each(list, function(index, list) {
    list[2]===null||list[2]===undefined||list[2]===''||isNaN(list[2])?tempWeight='':tempWeight=list[2].toFixed(2);
    if (!newTr) {
        // create new row
        newTr = $('<tr>');
        // do not reset it this time
        resetTr = false;
    } else {
        // we used the previous one so reset it this time
        resetTr = true;
    }
    newTr.appendTo($table)
        .append($('<td>').text(list[1]))
        .append($("<td><input type='text' name='txtCharge[]' value='"+tempWeight+"' onkeypress='return isNumberKey(event, this.value);'>"));

    if (resetTr) {
        // reset
        newTr = null;
    }
});
  • newTr contains the current tr being used or is null.
  • resetTr will decide if we reset newTr at the end of the loop.

[edit] Oh and of course you can uncomment the two heading cells




回答2:


You'll have to replace your $.each call with an actual for loop, and then inside your loop, create the td tags for index and index+1. Then the for loop should increment the index by 2 instead of by 1. That way, your loop is basically adding a row for every other index, and putting two indices per row.



来源:https://stackoverflow.com/questions/21863848/display-data-in-an-html-table-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!