【发布时间】:2020-12-06 19:04:15
【问题描述】:
我的 json 响应格式如下。
[{
"directory": "random_code",
"name": "random_code1",
"mailing_name": "random_code",
"address": "random_code",
"statutory": "random_code",
"state": "random_code",
"pincode": "random_code",
"telephone_num": "random_code",
"email": "random_code",
"currency_symbol": "h",
"maintain": "random_code",
"financial_year": "random_code1",
"books_beginning": "random_code1",
"educational_mode": "hj",
"vault_password": "hj",
"security_control": "h",
"curreny_formal_name": "jh",
"num_decimal_places": "jh",
"symbol_suffixed": "j",
"currency_symbol_decimal": "h",
"amount_in_millions": "jhj",
"space_between_symbol_amount": "h",
"decimal_places_for_printing_amount_in_words": "jhj"
}, {
"directory": "random_code",
"name": "random_code2",
"mailing_name": "random_code",
"address": "jh",
"statutory": "jh",
"state": "jhjhjh",
"pincode": "jh",
"telephone_num": "jh",
"email": "jhj",
"currency_symbol": "hj",
"maintain": "hj",
"financial_year": "random_code2",
"books_beginning": "random_code2",
"educational_mode": "h",
"vault_password": "hj",
"security_control": "hj",
"curreny_formal_name": "jh",
"num_decimal_places": "jhj",
"symbol_suffixed": "hjh",
"currency_symbol_decimal": "jh",
"amount_in_millions": "jh",
"space_between_symbol_amount": "jh",
"decimal_places_for_printing_amount_in_words": "jhh"
}]
我在脚本标签中的代码如下,id 名称是 datatable2 并希望 tp 显示所有从 ajax 响应到 Datatable 的数据。使用以下代码,我可以看到表中的值,但它不在 DataTables 中。
<table id="datatable2" class="table order-column hover">
<thead>
<tr>
<th>Name</th>
<th>Financial Year</th>
<th>Book Beginning from</th>
<th width="150px">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
$(function() {
$(document).ready(function() {
$.ajax({
url: "http://127.0.0.1:8000/api/company/",
dataType: "json",
type: 'GET',
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<tr><td>' + item.name + '</td><td>' + item.financial_year + '</td><td>' + item.books_beginning + '</td><td><a href="/company_app/edit/1/" class="btn ink-reaction btn-floating-action btn-warning"><i class="md md-edit"></i> </a><a href="/order/delete/1/" class="btn ink-reaction btn-floating-action btn-danger" onclick="return confirm(\'Are you sure you want to delete this?\')"><i class="md md-delete"></i> </a><a href="/order/1/" class="btn ink-reaction btn-floating-action btn-primary"><i class="md md-print"></i> </a></td></tr>';
});
$('#datatable2').append(trHTML);
}
});
});
});
</script>
但它没有添加到 dataTable 中。谁能帮我在数据表中附加相同的内容?我是数据表的菜鸟。
HTML 已编辑。
【问题讨论】:
-
为什么不保持简单并使用 Datatables 的内置 AJAX 功能呢? datatables.net/examples/ajax/simple.html
-
你确定是 HTML 表名 datatable2 吗?在 Chrome 上运行您的项目。右键单击您的数据表。在弹出菜单上选择检查元素。什么是 HTML 表格 ID?将此 id 用作选择器。
-
@RoryMcCrossan 你能详细说明我该如何使用它吗?我只想显示 4 个字段,即 name、financial_year、books_beginning 和 action 字段。如何在 DataTables() 中使用 ajax 属性来做到这一点?
-
@CAGDASAYDIN 是的,我确定。我已经更新了我的代码。请检查一下,让我知道解决方案。
标签: javascript jquery django ajax datatable