【发布时间】:2016-03-06 03:16:37
【问题描述】:
这不仅应该是一个简单的操作,而且我也在关注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);
}
样本数据(客户端)
编辑
正如 cmets 中所指出的,我在 success 回调中拼错了元素名称 dataTable。但是,现在我收到以下错误:
无法重新初始化 DataTable。要检索此表的 DataTables 对象,请不传递任何参数或查看 bRetrieve 和 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"} ] }); } });
【问题讨论】:
-
在您的 fn 顶部,您选择了
"#theTable",而在您的成功 fn 中,您选择了"#thetable"--- 是同一个元素吗?错字? -
不,我是个白痴,这是一个错字。谢谢
标签: javascript jquery json ajax datatable