使用JavaScript/jQuery在HTML表中显示数据 [英] Display data in an HTML table using JavaScript/jQuery

查看:49
本文介绍了使用JavaScript/jQuery在HTML表中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似以下的JSON响应.

 结果":[[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]] 

这对应于Java中的 java.util.List< Object []> .


以下JavaScript/jQuery函数接收响应.

  var超时;var request;$(函数(){var token = $("meta [name ='_ csrf']").attr("content");var header = $("meta [name ='_ csrf_header']").attr("content");$(document).ajaxSend(function(e,xhr,options){xhr.setRequestHeader(header,令牌);});});$(document).ready(function(){$(#zoneCharge").change(function(){如果(!请求){request = $ .ajax({数据类型:"json",输入:"POST",数据:JSON.stringify({jsonrpc:'2.0',方法:'getZoneCharges',id:'jsonrpc',params:[$(#zoneCharge").val()]}),contentType:"application/json-rpc; charset = utf-8",url:"ZoneChargeList",成功:功能(响应){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);'>"));});},完成:function(){超时=请求=空;},错误:功能(请求,状态,错误){if(status!==超时"&& status!==中止"){alert(status +:" + error);}}});超时= setTimeout(function(){如果(要求){request.abort();alert(请求已超时.");}},30000);}});});< span id ="zoneChargeList"></span> 

我想在格式.

如上面的等效快照所示,如何在四列的表中显示此列表?

id zoneCharge < select> 中选择一个项目时,将调用jQuery函数.

解决方案

类似的东西应该可以工作(这里有个小提琴来演示: 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);如果(!newTr){//创建新行newTr = $('< tr>');;//这次不要重置resetTr = false;} 别的 {//我们使用了上一个,因此这次将其重置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);'>"));如果(resetTr){//重启newTr = null;}}); 

  • newTr 包含当前正在使用的 tr 或为空.
  • resetTr 将决定我们是否在循环结束时重置 newTr .

[edit] 哦,当然,您可以取消注释两个标题单元格

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.


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

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

解决方案

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

这篇关于使用JavaScript/jQuery在HTML表中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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