javascript - 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"
}
]
解决方案
您可以动态创建表格并将其附加到如下元素:
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>
推荐阅读
- c++ - 试图编译 googletest 但出现以下错误:'::OpenThread' 尚未声明
- ios - 快速在右栏按钮项中添加徽章警报
- c# - MySQL C# 错误;“连接必须有效且打开”
- c - vxWorks 6.9下的shell会话和调试printf
- c - 如何在 Linux 上为 gcc 制作一个简单的 makefile
- java - 获取窗口状态
- python - 使用 3 空间坐标的 3 空间对象的体积
- sql - SQL Server 多连接
- javascript - 如何使用 JEST 测试 fetch API 类?
- r - 在 PATH 变量中引用 GPSBabel 以在 R 中使用