Я получаю следующую ошибку при попытке загрузить данные DataTables из источника ajax:
DataTables warning: table id=report-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Ниже мой DataTables html:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
Ниже приведен мой javascript DataTables:
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
Ниже приведен подтвержденный json, который мой контроллер С# возвращает для данных ajax DataTables:
{
"data":[
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
}
]
}
Ошибка, кажется, связана с форматом JSON, но не знаете, что не так?
РЕДАКТИРОВАТЬ:
Добавление полного кода javascript:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "@Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
3 ответа
Поскольку ваш ответ JSON является объектом, а не массивом, укажите ajax
, чтобы получить JsonResponse.data
, как показано ниже:
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": function (json) {
return json.data;
},
},
ИЛИ
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": "data"
},
$.ajax({
type: "POST",
url: "@Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (json) {
var data = json.data;
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data": data,
...
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
Выход
Ссылка
data
.
Источник данных должен быть массивом массивов, содержащих данные в tbody сказать
data = [
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"]
];
См. пример [https://datatables.net/examples/data_sources/js_array.html][1]
Кроме того, используйте data: data.data
вместо "ajax" : data
data: data.data
вместо "ajax" : data
Ваш блок <script>
должен выглядеть так, чтобы инициализировать ваши данные для ваших таблиц данных:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "@Url.Action("GetReportJson", "Report")",
dataType: "json",
method: "post",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data":data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
Похожие вопросы
Новые вопросы
c#
C # (произносится как «резкий») - это высокоуровневый, статически типизированный язык программирования с несколькими парадигмами, разработанный Microsoft. Код C # обычно нацелен на семейство инструментов и сред выполнения Microsoft .NET, включая, среди прочего, .NET Framework, .NET Core и Xamarin. Используйте этот тег для вопросов о коде, написанном на C # или в формальной спецификации C #.