首页 > 解决方案 > AJAX - JS - 从 AJAX 响应创建表并放入

问题描述

在这个方法中,我以文本形式传递了这个动作的响应,但是我想使用表格格式,我该怎么做?

function loadAditivos(){
    $('#aditivoAbertoInformacoesTexto').html('<div id="loaderMaiorDemandante"></div>');
    $("#loader").show();
    var jsonHide = $('#activeJsonHide').html();
    if(jsonHide) {
        $.ajax({
              url: 'search.action', // action to be perform
              type: 'POST',       //type of posting the data
              data: { dataJson: jsonHide }, // data to set to Action Class
              dataType: 'text',
              success: function (html) {
                  $("#loader").hide();
                  $('#showAdditiveasText').html(html); //How to pass a tablw to That DIV?
              },

        });
    }
}

如何使用表格格式将此数据传递给 div: "$('#showAdditiveasText').html(html)"?

例子:

[
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "sac@gmail.com"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "Binu@gmail.com"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "cal@gmail.com"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "nera@gmail.com"
  }
]

标签: javascripthtmljsonajax

解决方案


您可以动态创建表格并将其附加到如下元素:

var indices = ["UserID", "UserName", "Password", "Country", "Email"]
var data = [
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "sac@gmail.com"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "Binu@gmail.com"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "cal@gmail.com"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "nera@gmail.com"
  }
];

var table = $("<table>")
var thead = $('<thead>')
for(const index of indices) {
    $('<th>'+index+'</th>').appendTo(thead)
}
thead.appendTo(table)

var tbody = $('<tbody>')
for(const item of data) {
    var tr = $('<tr>')
    for(const index of indices) {
        $('<td>'+item[index]+'</td>').appendTo(tr)
  }
    tr.appendTo(tbody)
}
tbody.appendTo(table)

table.appendTo('#showAdditiveasText')
<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
<div id="showAdditiveasText"></div>


推荐阅读