Обновить таблицу данных jQuery
Было много вопросов об этом, но я не нашел того, который работал на меня. У меня есть простая и простая таблица HTML, чье тело заполняется строками из вызова AJAX.
Затем я хочу обновить таблицу плагином DataTable, но это не сработает.
У меня есть таблица HTML, которая выглядит так:
<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
В моей jQuery pageload
$(document).ready(function(){
var oTable = $('#myTable').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
И, наконец, моя функция dropdownlist change
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "@Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
var oTable = $('#myTable').dataTable(); // Nothing happens
var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
Добавление и т.д. было изменено, чтобы сократить его, и т.д., поэтому не сосредотачивайтесь на нем слишком много.
В основном возникает вопрос, как обновить таблицу, я могу сделать свой AJAX и добавить новые данные в таблицу, но плагин datatable не обновляет его.
Я пробовал другие вещи, такие как
.fnDraw(ложь);
Но он ничего не делает
Хотя я получаю ошибку JSON от
fnReloadAjax()
Любые подсказки о том, как обновить таблицу?
Ответы
Ответ 1
Попробуйте это
Сначала вы инициализировали таблицу, поэтому сначала очистите таблицу
$('#myTable').dataTable().fnDestroy();
Затем снова инициализируется после успеха ajax
$('#myTable').dataTable();
Подобно этому
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "@Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
$('#myTable').dataTable().fnDestroy();
$('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
DEMO
Ответ 2
Я знаю, что это старый пост, но я только что исследовал проблему и нашел самый простой способ ее решения в man-страницах DataTable: https://datatables.net/reference/api/ajax.reload%28%29
Все, что вам нужно вызвать table.ajax.reload();
Ответ 3
var table = $('#product_table').DataTable({
"bProcessing": true,
"serverSide": true,
responsive: true,
"ajax": {
url: get_base_url + "product_table", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function () {
$("#employee_grid_processing").css("display", "none");
}
}
});
//call this funtion
$(document).on('click', '#view_product', function () {
table.ajax.reload();
});
Ответ 4
Я сделал кое-что, что связано с этим... Ниже приведен пример javascript с тем, что вам нужно. Здесь есть демо: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}
Ответ 5
Начиная с версии 1.10.0, вы можете использовать ajax.reload() api.
var table = $('#myTable').DataTable();
table.ajax.reload();
Имейте в виду использовать $('#myTable').DataTable()
, а не $('#myTable').DataTable()