A] 问题总结:
jquery 数据表的数据是使用 javascript 函数生成的,该函数解析 python 返回的 JSON 数据。 浏览器中生成的 HTML 表正确显示,但 jquery 数据表无法识别数据,数据表功能无法正常工作。当我查看 HTML 页面源代码时,我也看不到表格中的数据。
B] 代码摘录:
1) jQuery 数据表设置:
/* Define two custom functions (asc and desc) for string sorting */
jQuery.fn.dataTableExt.oSort['string-case-asc'] = function(x,y) {
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
$(document).ready(function() {
$('#datatable_for_current_users').dataTable( {
"aaSorting": [ [3,'desc'] ],
"aoColumns": [
null,
null,
{ "sType": 'string-case' },
null
]
});
});
2) jQuery 数据表的 HTML 表设置:
<div id="your_city">
<!-- Table containing the data to be printed-->
<table cellpadding="0" cellspacing="0" border="0" class="display" id="datatable_for_current_users">
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Status</th>
<th>Reported at</th>
</tr>
</thead>
<tbody>
<!-- contents of the tbody will be loaded by javascript method XXX -->
</tbody>
</table>
</div>
3) 解析从 python 返回的 JSON 输出并填充数据表的“tbody”的 Javascript:
这里 javascript 将用户国家和城市发送给 python 代码。 Python 代码然后找出特定用户的数据库对象,并将 JSON 数据发送回 javascript。
$.post("/AjaxRequest", {
selected_country_name: $users_country,
selected_city_name: $users_city
},
function LoadUsersDatatable(data) {
var tbody = $("#datatable_for_current_users > tbody").html("");
jsonData = jQuery.parseJSON(data);
for (var i = 0; i < jsonData.length; i++) {
var citydata = jsonData[i];
var rowText = "<tr class='gradeA'><td>" + citydata.city.country.country_name + "</td><td>" + citydata.city.city_name + "</td><td>" + citydata.status + "</td><td>" + citydata.date_time.ctime + "</td></tr>";
$(rowText).appendTo(tbody);
}
}
);
4) 呈现 HTML 页面时,我检查了数据表的“tbody”,它是空的:
<tbody>
<!-- contents of the tbody will be loaded by javascript method XXX -->
</tbody>
在我看来这就是问题所在
但是在浏览器中,我看到表格被正确加载,但是数据表显示 0 个条目并且搜索排序功能清空了表格
最佳答案
不是简单地将原始 html 附加到表体,您必须使用 DataTables fnAddData
方法来获取新行。
所以对你来说,你的代码看起来像这样
var dt = $('#datatable_for_current_users').dataTable();
....
dt.fnAddData({DT_RowClass: 'gradeA', 0: citydata.city.country.country_name, 1: citydata.city.city_name, 2: citydata.status, 3: citydata.date_time.ctime}, true);
末尾的 true
只是在添加行后重新绘制表格。如果需要,您可以将其更改为 false
并在循环完成后调用 dt.fnDraw();
以一次添加所有行
关于javascript - 当使用 Javascript 填充表数据时,jQuery 数据表功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5743546/