Anonymous
Динамическое разбиение на страницы с использованием JavaScript Datatable не работает? [закрыто]
Сообщение
Anonymous » 20 сен 2024, 05:47
При повторной инициализации отображается предупреждение, а существующая нумерация страниц отсутствует, текущая нумерация страниц показывает только 50 записей по умолчанию.
В качестве альтернативы я реализовал другую нумерацию страниц, которая работает, но мне нужна встроенная разбивка на страницы javascript.
Ниже приведен мой код. Я включил все ссылки dataTable, но разбивка на страницы не соответствует моим полученным данным-
Код: Выделить всё
Journal Subscriptions and Revenue
Name
Cust_No_
Journal_ID
Content_Year
Subject
Journal_Title
Type_of_Subscription
[url=?page=
Loading more data...
let currentPage = 1;
let totalPages = 1;
let loading = false;
function loadData(page) {
$.ajax({
url: 'journal_data_19.php',
type: 'GET',
data: { page: page },
dataType: 'json',
success: function(data) {
if (data.error) {
alert('Error: ' + data.error);
return;
}
totalPages = data.totalPages;
currentPage = data.currentPage;
const tableBody = $('#table-body');
tableBody.empty(); // Clear existing data
data.results.forEach(row => {
tableBody.append(
`
${row.Name}
${row.Cust_No_}
${row.Journal_ID}
${row.Content_Year}
${row.Subject}
${row.Journal_Title}
${row.Type_of_Subscription}
`
);
});
updatePagination();
},
error: function(xhr, status, error) {
console.error('AJAX Error:', status, error);
}
});
}
function updatePagination() {
const paginationElement = document.getElementById('pagination');
if (paginationElement) {
let paginationHtml = '';
// Previous button
if (currentPage > 1) {
paginationHtml += `[url=#]Previous[/url] `;
}
// Page numbers
for (let i = 1; i {
tableBody.append(
`
${row.Name}
${row.Cust_No_}
${row.Journal_ID}
${row.Content_Year}
${row.Subject}
${row.Journal_Title}
${row.Type_of_Subscription}
`
);
});
loading = false;
$('#loading-message').hide();
},
error: function(xhr, status, error) {
console.error('AJAX Error:', status, error);
loading = false;
$('#loading-message').hide();
}
});
}
$(document).ready(function() {
loadData(currentPage); // Initial load
// Event listener for scrolling
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100 && !loading && currentPage < totalPages) {
loadMoreData(++currentPage);
}
});
});
//JAVASCRIPT INBUILT PAGINATION SECTION---------------------
$(document).ready(function() {
$('#bootstrap-data-table-export').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "journal_data_19.php",
"type": "GET",
"dataSrc": function (json) {
// Check if json.data exists and contains data
if (json.data && json.data.length > 0) {
return json.data;
} else {
console.error('No data found or incorrect format');
return [];
}
},
"error": function (xhr, error, thrown) {
console.error('An error occurred while fetching data:', error);
}
},
"pageLength": 50,
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"columns": [
{ "data": "Name" },
{ "data": "Cust_No_" },
{ "data": "Journal_ID" },
{ "data": "Content_Year" },
{ "data": "Type_of_Subscription" },
{ "data": "Journal_Title" },
{ "data": "Subject" }
],
"paging": true,
"searching": true,
"ordering": true,
"dom": 'Bfrtip',
"buttons": ['copy', 'csv', 'excel', 'pdf', 'print'],
"scrollY": "500px",
"scrollCollapse": true,
"responsive": true
});
});
Это мой PHP-код-
На изображении выше показано, как показаны обе мои нумерации страниц: моя пользовательская нумерация страниц показывает точное количество страниц согласно моим записям, но встроенная таблица данных javascript показывает только 50 записей
Подробнее здесь:
https://stackoverflow.com/questions/790 ... ot-working
1726800434
Anonymous
При повторной инициализации отображается предупреждение, а существующая нумерация страниц отсутствует, текущая нумерация страниц показывает только 50 записей по умолчанию. В качестве альтернативы я реализовал другую нумерацию страниц, которая работает, но мне нужна встроенная разбивка на страницы javascript. Ниже приведен мой код. Я включил все ссылки dataTable, но разбивка на страницы не соответствует моим полученным данным- [code] Journal Subscriptions and Revenue Name Cust_No_ Journal_ID Content_Year Subject Journal_Title Type_of_Subscription [url=?page= Loading more data... let currentPage = 1; let totalPages = 1; let loading = false; function loadData(page) { $.ajax({ url: 'journal_data_19.php', type: 'GET', data: { page: page }, dataType: 'json', success: function(data) { if (data.error) { alert('Error: ' + data.error); return; } totalPages = data.totalPages; currentPage = data.currentPage; const tableBody = $('#table-body'); tableBody.empty(); // Clear existing data data.results.forEach(row => { tableBody.append( ` ${row.Name} ${row.Cust_No_} ${row.Journal_ID} ${row.Content_Year} ${row.Subject} ${row.Journal_Title} ${row.Type_of_Subscription} ` ); }); updatePagination(); }, error: function(xhr, status, error) { console.error('AJAX Error:', status, error); } }); } function updatePagination() { const paginationElement = document.getElementById('pagination'); if (paginationElement) { let paginationHtml = ''; // Previous button if (currentPage > 1) { paginationHtml += `[url=#]Previous[/url] `; } // Page numbers for (let i = 1; i { tableBody.append( ` ${row.Name} ${row.Cust_No_} ${row.Journal_ID} ${row.Content_Year} ${row.Subject} ${row.Journal_Title} ${row.Type_of_Subscription} ` ); }); loading = false; $('#loading-message').hide(); }, error: function(xhr, status, error) { console.error('AJAX Error:', status, error); loading = false; $('#loading-message').hide(); } }); } $(document).ready(function() { loadData(currentPage); // Initial load // Event listener for scrolling $(window).scroll(function() { if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100 && !loading && currentPage < totalPages) { loadMoreData(++currentPage); } }); }); //JAVASCRIPT INBUILT PAGINATION SECTION--------------------- $(document).ready(function() { $('#bootstrap-data-table-export').DataTable({ "processing": true, "serverSide": true, "ajax": { "url": "journal_data_19.php", "type": "GET", "dataSrc": function (json) { // Check if json.data exists and contains data if (json.data && json.data.length > 0) { return json.data; } else { console.error('No data found or incorrect format'); return []; } }, "error": function (xhr, error, thrown) { console.error('An error occurred while fetching data:', error); } }, "pageLength": 50, "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]], "columns": [ { "data": "Name" }, { "data": "Cust_No_" }, { "data": "Journal_ID" }, { "data": "Content_Year" }, { "data": "Type_of_Subscription" }, { "data": "Journal_Title" }, { "data": "Subject" } ], "paging": true, "searching": true, "ordering": true, "dom": 'Bfrtip', "buttons": ['copy', 'csv', 'excel', 'pdf', 'print'], "scrollY": "500px", "scrollCollapse": true, "responsive": true }); }); [/code] Это мой PHP-код- [code] [/code] [img]https://i.sstatic.net/Dd9fRah4.png[/img] На изображении выше показано, как показаны обе мои нумерации страниц: моя пользовательская нумерация страниц показывает точное количество страниц согласно моим записям, но встроенная таблица данных javascript показывает только 50 записей Подробнее здесь: [url]https://stackoverflow.com/questions/79001763/dynamic-pagination-using-javascript-datatable-is-not-working[/url]