这不仅应该是一个简单的操作,而且我遵循 documentation以及。我有一个返回 json
数据集的 ajax 调用。我已成功清除表,但调用 success
方法时什么也没有发生。 console
语句显示正在返回数据...但表仍为空。知道为什么吗?
JS
$('#SortByCoverage').click(function () {
var table = $('#theTable').DataTable();
table.fnClearTable();
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#thetable").dataTable({
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
服务器端代码
public JsonResult Question2()
{
var ads = _client.GetAdDataByDateRange(new DateTime(2011, 1, 1), new DateTime(2011, 4, 1));
var json = ads.Where(x => x.Position.Equals("Cover") && x.NumPages >= (decimal)0.5).Select(x => new{
AdId = x.AdId,
BrandId = x.Brand.BrandId,
BrandName = x.Brand.BrandName,
NumPages = x.NumPages,
Position = x.Position
});
return Json(json, JsonRequestBehavior.AllowGet);
}
示例数据(客户端)
编辑
正如评论中所指出的,我在 success
回调中拼错了元素名称 dataTable
。但是,现在我收到以下错误:
Cannot reinitialise DataTable. To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
一旦表变得清晰,我真的必须销毁该表才能重新加载数据吗?
我添加了
bRetrieve
和bDestroy
。这消除了错误,但仍然没有新数据加载到表中。$.ajax({ url: '@Url.Action("Question2", "Home")', type: 'GET', dataType: 'json', success: function (data) { console.log(data); $("#theTable").dataTable({ //"bRetrieve": true, "bDestroy": true, "aaData": data, "aoColumns": [ {title:"AdId"}, {title:"BrandId"}, {title:"BrandName"}, {title:"NumPages"}, {title:"Position"} ] }); } });
最佳答案
我会做一些不同的事情,看看如何:
var theTable = $("#thetable").dataTable({
"aaData": [],
"aoColumns": [
{data:"AdId"},
{data:"BrandId"},
{data:"BrandName"},
{data:"NumPages"},
{data:"Position"}
]
}).DataTable();
$('#SortByCoverage').click(function () {
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
theTable.clear().draw();
table.rows.add(data)
.draw();
}
});
关于javascript - Datatables 不会重新加载 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34033292/