使用 jQuery 从 AJAX 响应(json)构建表行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17724017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery to build table rows from AJAX response(json)
提问by Canttouchit
Possible duplicate Nested elements
可能重复的嵌套元素
I'm getting from server-side ajax response (Json) and I'm trying to dynamically create table rows and append them to an existing table with id=records_table
.
我从服务器端 ajax 响应(Json)获取,我正在尝试动态创建表行并将它们附加到 id= 的现有表中records_table
。
I tried to implement the solution in possible duplicate but it failed.
我试图以可能的重复方式实施该解决方案,但它失败了。
My response looks like that:
我的回答是这样的:
'[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]'
the require result is something like that:
要求结果是这样的:
<tr>
<td>9</td>
<td>Alon</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>Tala</td>
<td>5</td>
</tr>
I want to do something without parsing the Json so I tried to do the following, which of course was a disaster:
我想在不解析 Json 的情况下做一些事情,所以我尝试执行以下操作,这当然是一场灾难:
function responseHandler(response)
{
$(function() {
$.each(response, function(i, item) {
$('<tr>').html(
$('td').text(item.rank),
$('td').text(item.content),
$('td').text(item.UID)
).appendTo('#records_table');
});
});
}
From my solution I get only one row with the number 6 in all cells. What am I doing wrong?
从我的解决方案中,我只得到所有单元格中数字为 6 的一行。我究竟做错了什么?
回答by drizzie
Use .append instead of .html
使用 .append 而不是 .html
var response = "[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]";
// convert string to JSON
response = $.parseJSON(response);
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.rank),
$('<td>').text(item.content),
$('<td>').text(item.UID)
); //.appendTo('#records_table');
console.log($tr.wrap('<p>').html());
});
});
回答by Neeraj Singh
Try this (DEMO link updated):
试试这个(演示链接已更新):
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
回答by hmkcode
Here is a complete answer from hmkcode.com
这是来自hmkcode.com的完整答案
If we have such JSON data
如果我们有这样的 JSON 数据
// JSON Data
var articles = [
{
"title":"Title 1",
"url":"URL 1",
"categories":["jQuery"],
"tags":["jquery","json","$.each"]
},
{
"title":"Title 2",
"url":"URL 2",
"categories":["Java"],
"tags":["java","json","jquery"]
}
];
And we want to view in this Table structure
而我们想在这个表结构中查看
<table id="added-articles" class="table">
<tr>
<th>Title</th>
<th>Categories</th>
<th>Tags</th>
</tr>
</table>
The following JS code will fill create a row for each JSON element
以下 JS 代码将为每个 JSON 元素填充创建一行
// 1. remove all existing rows
$("tr:has(td)").remove();
// 2. get each article
$.each(articles, function (index, article) {
// 2.2 Create table column for categories
var td_categories = $("<td/>");
// 2.3 get each category of this article
$.each(article.categories, function (i, category) {
var span = $("<span/>");
span.text(category);
td_categories.append(span);
});
// 2.4 Create table column for tags
var td_tags = $("<td/>");
// 2.5 get each tag of this article
$.each(article.tags, function (i, tag) {
var span = $("<span/>");
span.text(tag);
td_tags.append(span);
});
// 2.6 Create a new row and append 3 columns (title+url, categories, tags)
$("#added-articles").append($('<tr/>')
.append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
.append(td_categories)
.append(td_tags)
);
});
回答by tymeJV
Try it like this:
像这样尝试:
$.each(response, function(i, item) {
$('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table');
});
回答by YD1m
You shouldn't create jquery objects for each cell and row. Try this:
您不应该为每个单元格和行创建 jquery 对象。尝试这个:
function responseHandler(response)
{
var c = [];
$.each(response, function(i, item) {
c.push("<tr><td>" + item.rank + "</td>");
c.push("<td>" + item.content + "</td>");
c.push("<td>" + item.UID + "</td></tr>");
});
$('#records_table').html(c.join(""));
}
回答by Iftikhar Khan
$.ajax({
type: 'GET',
url: urlString ,
dataType: 'json',
success: function (response) {
var trHTML = '';
for(var f=0;f<response.length;f++) {
trHTML += '<tr><td><strong>' + response[f]['app_action_name']+'</strong></td><td><span class="label label-success">'+response[f]['action_type'] +'</span></td><td>'+response[f]['points']+'</td></tr>';
}
$('#result').html(trHTML);
$( ".spin-grid" ).removeClass( "fa-spin" );
}
});
回答by Cybernetic
Data as JSON:
数据为JSON:
data = [
{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}
]
You can use jQueryto iterate over JSON and create tables dynamically:
您可以使用jQuery遍历 JSON 并动态创建表:
num_rows = data.length;
num_cols = size_of_array(data[0]);
table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");
header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);
$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})
Here is the size_of_array function:
这是 size_of_array 函数:
function size_of_array(obj) {
size = Object.keys(obj).length;
return(size)
};
You can also add stylingif needed:
如果需要,您还可以添加样式:
$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');
Result:
结果:
OR USE AZLE
或使用AZLE
In Azleyou simply add JSON data to create a table as follows:
在Azle 中,您只需添加 JSON 数据即可创建一个表,如下所示:
Add a sectionwith a holding div:
添加一个带有控股 div的部分:
az.add_sections({
"this_class": "my_sections",
"sections": 1
})
az.add_html('my_sections', 1, {
"html": "<div class='holdng_div'></div>"
})
Create a wrapped function that draws the table. Here I use Azle's add_layout, and fill_rowfunctions, along with some looping and styling:
创建一个绘制表格的包装函数。在这里,我使用了 Azle 的add_layout和fill_row函数,以及一些循环和样式:
function draw_table(data) {
az.add_layout('holdng_div', 1, {
"this_class": "my_table",
"row_class": "my_table_rows",
"cell_class": "my_table_cells",
"number_of_rows": data.length,
"number_of_columns": 5
})
data_ = data
az.fill_row('my_table', 1, {
"header": false,
"cell_class": "my_table_cells",
"text_class": "header_text",
"row_number": 1,
"array": Object.keys(data[0])
})
az.all_style_text('header_text', {
"color": "yellow",
"font-family": "Arial"
})
az.call_multiple({
"iterations": data.length,
"function": function() {
az.fill_row('my_table', 1, {
"header": true,
"cell_class": "my_table_cells",
"row_number": index + 1,
"array": [data_[index]['sepalLength'],data_[index]['sepalWidth'],data_[index]['petalLength'],data_[index]['petalWidth'],data_[index]['species']]
})
}
})
az.alternate_row_color('my_table', 1, 'whitesmoke', '#33AADE', 'black', 'black', true)
}
Finally, call an API that returns data(here I use the Iris dataset hosted on Github) and pass that data onto our wrapped function:
最后,调用返回数据的 API(这里我使用 Github 上托管的 Iris 数据集)并将该数据传递给我们的包装函数:
az.call_api({
"url": "https://raw.githubusercontent.com/domoritz/maps/master/data/iris.json",
"parameters": {},
"done": function() {
draw_table(data)
}
})
Result:
结果:
Here is the GIST
这是GIST
Here is the FIDDLE
这是小提琴
回答by M_R_K
I have created this JQuery function
我已经创建了这个 JQuery 函数
/**
* Draw a table from json array
* @param {array} json_data_array Data array as JSON multi dimension array
* @param {array} head_array Table Headings as an array (Array items must me correspond to JSON array)
* @param {array} item_array JSON array's sub element list as an array
* @param {string} destinaion_element '#id' or '.class': html output will be rendered to this element
* @returns {string} HTML output will be rendered to 'destinaion_element'
*/
function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) {
var table = '<table>';
//TH Loop
table += '<tr>';
$.each(head_array, function (head_array_key, head_array_value) {
table += '<th>' + head_array_value + '</th>';
});
table += '</tr>';
//TR loop
$.each(json_data_array, function (key, value) {
table += '<tr>';
//TD loop
$.each(item_array, function (item_key, item_value) {
table += '<td>' + value[item_value] + '</td>';
});
table += '</tr>';
});
table += '</table>';
$(destinaion_element).append(table);
}
;
回答by Kunal Mukherjee
You could do it something like this:
你可以这样做:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function(){
$.ajax({
url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
data: '<any parameters you want to send as the Request body or query string>',
dataType: json,
async: true,
method: "GET"
success: function(data){
//If the REST API returned a successful response it'll be stored in data,
//just parse that field using jQuery and you're all set
var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td>' + value + '</td>';
});
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('#tblSomething').html(tblSomething);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
});
</script>
<table id = "tblSomething" class = "table table-hover"></table>
回答by Harpreet
I do following to get JSON response from Ajax and parse without using parseJson:
我执行以下操作以从 Ajax 获取 JSON 响应并在不使用 parseJson 的情况下进行解析:
$.ajax({
dataType: 'json', <----
type: 'GET',
url: 'get/allworldbankaccounts.json',
data: $("body form:first").serialize(),
If you are using dataType as Text then you need $.parseJSON(response)
如果你使用 dataType 作为 Text 那么你需要 $.parseJSON(response)