【问题标题】:How to do pagination of table data using the received JSON table data in client side without bootstrap?如何在没有引导程序的情况下在客户端使用接收到的 JSON 表数据对表数据进行分页?
【发布时间】:2020-03-11 15:26:54
【问题描述】:

我已经使用 PHP 服务器页面以 JSON 形式接收表格行数据,并在每个新的搜索条件显示新表格时收到 JSON 表格行。但问题是当我有更多行数时,我想对其进行分页并允许用户选择他想要查看的行数,例如 10、20、30。

简而言之,我想达到以下结果:

如果行数为 200 并且用户希望一次查看 25 行,则 200/25 表示(上一个 1->2->3->4.....->8 下一个)8 个数字显示在表格的顶部,允许用户跳转到所需的页面并查看行。

更新:您可以在下面的答案中查看我的最新作品。

我在loadtable.js 文件中尝试了以下内容,如下所示。我还附加了我的服务器端 PHP 文件search.php 和客户端脚本loadtable.js,它们正在处理 JSON 数据并执行分页任务。

//###########################################
// Pagination code start
//###########################################

$("#pagination").attr('style','display:block;');

$("#pagination").html("<p1>Total number of records fetched: "+result.length+"</p1><h5 style='display: inline-block;float:left;width: 150px;'>Number of rows/page: &nbsp;&nbsp; &nbsp;&nbsp;<select id='number-of-records-per-page' onchange='num_of_records(this)' style='width:60px;'><option value='10'>10</option><option value='20'>20</option><option value='30'>30</option><option value='40'>40</option><option value='50'>50</option></select></h5><br><br>");

$("#pagination").append("<div id='nav-pagination' style='float:left;'><a href='#'>&laquo;</a><a class='active' href='#'>1</a></div>");

var total_num_of_rows = result.length;

var number_of_rows_per_page = $('#pagination').find('#number-of-records-per-page option:selected').val();

console.log(total_num_of_rows)
console.log(number_of_rows_per_page)

for (i = 1; i < total_num_of_rows/number_of_rows_per_page; i++) {

     $("#nav-pagination").append("<a href='#'>"+(i+1)+"</a>");

}

$("#nav-pagination").append("<a href='#'>&raquo;</a></div>");

 //###########################################
// Pagination code end
//###########################################

问题是我在 ajax 成功函数success:function(data){ 中进行分页,我认为当从服务器端接收到 JSON 结果时会调用一次。也因为我是 ajax 的初学者,感觉很难继续。请帮忙。

客户端脚本loadtable.js的完整代码

// This is script to load table based on filter section

$(document).ready(function() {

var delay = 1000;

// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {

$('#load-csv-file-button').attr('style','display:none;');
$("#filterRecords").attr('style','display:block;');
$('#add_lead_info').attr('style','display:none;');

e.preventDefault();

var lead_owner = $('#filterformpost').find('#lead_owner_select option:selected').val();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();        

$.ajax({
type: "POST",
url: "./server/search.php",
data: {
"lead_owner": lead_owner,
"lead_status": lead_status,
"campaign_status": campaign_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.search_lead_filter_message_box').html(
    '<img src="tenor.gif" width="40" height="40"/>'
);
},

success:function(data){

var result = $.parseJSON(data);                       

$("#filterRecords").empty();

//###########################################
// Pagination code start
//###########################################

$("#pagination").attr('style','display:block;');

$("#pagination").html("<p1>Total number of records fetched: "+result.length+"</p1><h5 style='display: inline-block;float:left;width: 150px;'>Number of rows/page: &nbsp;&nbsp; &nbsp;&nbsp;<select id='number-of-records-per-page' onchange='num_of_records(this)' style='width:60px;'><option value='10'>10</option><option value='20'>20</option><option value='30'>30</option><option value='40'>40</option><option value='50'>50</option></select></h5><br><br>");

$("#pagination").append("<div id='nav-pagination' style='float:left;'><a href='#'>&laquo;</a><a class='active' href='#'>1</a></div>");

var total_num_of_rows = result.length;

var number_of_rows_per_page = $('#pagination').find('#number-of-records-per-page option:selected').val();

console.log(total_num_of_rows)
console.log(number_of_rows_per_page)

for (i = 1; i < total_num_of_rows/number_of_rows_per_page; i++) {

     $("#nav-pagination").append("<a href='#'>"+(i+1)+"</a>");

}

$("#nav-pagination").append("<a href='#'>&raquo;</a></div>");

 //###########################################
// Pagination code end
//###########################################

var table='';

table = $("<table></table>");

table.append('<thead><th>#</th><th>Lead Name</th><th>Company</th><th>Email</th><th>Phone</th><th>Lead Owner</th></thead>'); 

table.append('<tbody></tbody>'); 

var i = 1;

$.each(result, function(key, value) {

    table.last().append("<tr><td>" + i + "</td><td><a target='_blank' href=./lead/index.html?lead_id="+ value['Lead_Id'] + " </a>" + value['FirstName'] + ' ' + value['LastName'] + "</td><td>" + value['Company'] + "</td><td><a href=mailto:" + value['Email'] + ">" + value['Email'] + "</a></td><td>" + value['Phone'] + "</td><td><a target='_blank' href=./account/index.html?user_id="+ value['LeadAddedBy'] + " </a>" + value['LeadAddedBy'] + "</td></tr>" );

    i = i + 1;                

});

table.after().append("<br><br>");               

$("#filterRecords").html(table);
$('.search_lead_filter_message_box').html('');

}           

});

});


});

【问题讨论】:

  • 这有用吗stackoverflow.com/questions/42152944/…,但在这个引导程序中使用
  • 你为什么不使用引导数据表的内置功能?你可以在哪里执行服务器端分页等,你想要的一切
  • 因为自从我开始我的项目以来我没有使用过引导程序,这就是为什么我不想在两者之间使用
  • 我在答案部分粘贴了我的一些问题,如果你能解决它们会很棒
  • @AkhtarMunir 你有什么建议

标签: javascript jquery html ajax


【解决方案1】:

我尝试使用 JSON 数据在 JSFiddle (https://jsfiddle.net/rinku16/hn3t9gz6/33/) 中完成分页,但现在的问题是它无法正确显示每页的行数。

我做了一个单独的函数来处理 JSON 数据并显示结果。

但我面临以下小问题:

1) 尽管我尝试更改 var elements_per_page = 3; 的值,但每页的行数无法正常工作。我还想选择用户选择选项来查看他想查看的每页的行数。如下图所示。

2) overflow-x 样式也无法正常工作,如下图所示。

3) 我还想使用 CSS focus 属性来了解用户是哪个页面 class=nav 上一个和下一个之间的 1,2,3,4 按钮。

客户端的JSON数据进行分页。

var userDetails = [

  {
    "Lead_Id": "66",
    "FirstName": "John",
    "LastName": "Doe",
    "Company": "Google",
    "Website": "www.google.com",
    "Designation": "Manager",
    "Linkedin": "www.linkedin.com\/john-doe",
    "Email": "johndoe@google.com",
    "Phone": "5125501553",
    "State": "Delaware",
    "Country": "USA",
    "TechArea": "Cloud computing",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-02-03",
    "NextContactDate": "2020-02-29",
    "LeadDescription": "This is lead description testing",
    "OwnerNotes": null,
    "SetReminder": "2020-02-29",
    "AdminNotes": "This is admin notes testing",
    "LeadStatus": "Planned",
    "LeadAddedBy": "28",
    "LeadAddedOn": "2020-02-03 16:28:26",
    "LeadUpdatedBy": null,
    "LeadUpdatedOn": null
  },

  {
    "Lead_Id": "67",
    "FirstName": "Tohn",
    "LastName": "Doe",
    "Company": "Microsoft",
    "Website": "www.microsoft.com",
    "Designation": "Manager",
    "Linkedin": "www.linkedin.com\/tohn-doe",
    "Email": "tohn@microsoft.com",
    "Phone": "123456",
    "State": "California",
    "Country": "USA",
    "TechArea": "Computer Networks",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-03-05",
    "NextContactDate": "2020-03-07",
    "LeadDescription": "This is test lead description",
    "OwnerNotes": null,
    "SetReminder": "2020-03-11",
    "AdminNotes": "This is testing admin notes",
    "LeadStatus": "Planned",
    "LeadAddedBy": "18",
    "LeadAddedOn": "2020-03-05 10:47:21",
    "LeadUpdatedBy": null,
    "LeadUpdatedOn": null
  },

  {
    "Lead_Id": "122",
    "FirstName": "Test1",
    "LastName": "User1",
    "Company": "NA",
    "Website": "NA",
    "Designation": "Tester",
    "Linkedin": "NA",
    "Email": "test1@test.com",
    "Phone": "7508023064",
    "State": "Chandigarh",
    "Country": "India",
    "TechArea": "Computers",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-03-05",
    "NextContactDate": "2020-03-05",
    "LeadDescription": "Testing Lead Description",
    "OwnerNotes": "Testing Owner Notes",
    "SetReminder": "2020-03-05",
    "AdminNotes": "This is testing admin notes",
    "LeadStatus": "Planned",
    "LeadAddedBy": "18",
    "LeadAddedOn": "2020-03-05 17:34:25",
    "LeadUpdatedBy": null,
    "LeadUpdatedOn": null
  },

  {
    "Lead_Id": "123",
    "FirstName": "Test2",
    "LastName": "User2",
    "Company": "NA",
    "Website": "NA",
    "Designation": "Tester",
    "Linkedin": "NA",
    "Email": "test2@test.com",
    "Phone": "7508023064",
    "State": "Chandigarh",
    "Country": "India",
    "TechArea": "Computers",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-03-05",
    "NextContactDate": "2020-03-05",
    "LeadDescription": "Testing Lead Description",
    "OwnerNotes": "Testing Owner Notes",
    "SetReminder": "2020-03-05",
    "AdminNotes": "This is testing admin notes",
    "LeadStatus": "Planned",
    "LeadAddedBy": "18",
    "LeadAddedOn": "2020-03-05 17:34:25",
    "LeadUpdatedBy": null,
    "LeadUpdatedOn": null
  },

  {
    "Lead_Id": "124",
    "FirstName": "Test3",
    "LastName": "",
    "Company": "NA",
    "Website": "NA",
    "Designation": "Tester",
    "Linkedin": "NA",
    "Email": "test3@test.com",
    "Phone": "7508023064",
    "State": "Chandigarh",
    "Country": "India",
    "TechArea": "Computers",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-03-05",
    "NextContactDate": "2020-03-05",
    "LeadDescription": "Testing Lead Description",
    "OwnerNotes": "Testing Owner Notes",
    "SetReminder": "2020-03-05",
    "AdminNotes": "",
    "LeadStatus": "Planned",
    "LeadAddedBy": "18",
    "LeadAddedOn": "2020-03-06 10:54:12",
    "LeadUpdatedBy": null,
    "LeadUpdatedOn": null
  },

  {
    "Lead_Id": "125",
    "FirstName": "Test4",
    "LastName": "User4",
    "Company": "",
    "Website": "NA",
    "Designation": "",
    "Linkedin": "NA",
    "Email": "test4@test.com",
    "Phone": "7508023064",
    "State": "Chandigarh",
    "Country": "India",
    "TechArea": "Computers",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-03-05",
    "NextContactDate": "2020-03-05",
    "LeadDescription": "Testing Lead Description",
    "OwnerNotes": "",
    "SetReminder": "2020-03-05",
    "AdminNotes": "This is testing admin notes",
    "LeadStatus": "",
    "LeadAddedBy": "18",
    "LeadAddedOn": "2020-03-06 10:54:12",
    "LeadUpdatedBy": null,
    "LeadUpdatedOn": null
  },

  {
    "Lead_Id": "126",
    "FirstName": "Test5",
    "LastName": "",
    "Company": "NA",
    "Website": "NA",
    "Designation": "Tester",
    "Linkedin": "NA",
    "Email": "test5@test.com",
    "Phone": "7508023064",
    "State": "Chandigarh",
    "Country": "India",
    "TechArea": "Computers",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-03-05",
    "NextContactDate": "2020-03-05",
    "LeadDescription": "This is test description",
    "OwnerNotes": "Testing Owner Notes",
    "SetReminder": "2020-03-05",
    "AdminNotes": "This is testing admin notes",
    "LeadStatus": "Planned",
    "LeadAddedBy": "18",
    "LeadAddedOn": "2020-03-06 10:54:12",
    "LeadUpdatedBy": "18",
    "LeadUpdatedOn": "2020-03-06 10:55:08"
  },

  {
    "Lead_Id": "127",
    "FirstName": "John",
    "LastName": "Doe",
    "Company": "Google",
    "Website": "www.google.com",
    "Designation": "Manager",
    "Linkedin": "www.linkedin.com\/john-doe",
    "Email": "johndoe@google.com",
    "Phone": "5125501553",
    "State": "Delaware",
    "Country": "USA",
    "TechArea": "Cloud computing",
    "FirmType": "Corporate",
    "FirmSize": "Less than 10",
    "LastContactDate": "2020-02-03",
    "NextContactDate": "2020-02-29",
    "LeadDescription": "This is lead description testing",
    "OwnerNotes": null,
    "SetReminder": "2020-02-29",
    "AdminNotes": "This is admin notes testing",
    "LeadStatus": "Planned",
    "LeadAddedBy": "28",
    "LeadAddedOn": "2020-02-03 16:28:26",
    "LeadUpdatedBy": null,
    "LeadUpdatedOn": null
  }

];

下面是客户端最新的脚本。

// This is script to load table based on filter section

$(document).ready(function() {

var delay = 1000;

// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {

    $('#load-csv-file-button').attr('style','display:none;');
     $("#filterRecords").attr('style','display:block;');
     $('#add_lead_info').attr('style','display:none;');

    e.preventDefault();

    var lead_owner = $('#filterformpost').find('#lead_owner_select option:selected').val();
    var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
    var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
    var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
    var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
    var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
    var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
    var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
    var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
    var start_date = $('#filterformpost').find('#start_date_search').val();
    var end_date = $('#filterformpost').find('#end_date_search').val();        

    $.ajax({
        type: "POST",
        url: "./server/search.php",
        data: {
            "lead_owner": lead_owner,
            "lead_status": lead_status,
            "campaign_status": campaign_status,
            "company_name": company_name,
            "tech_area": tech_area,
            "firm_size": firm_size,
            "firm_type": firm_type,
            "country_name": country_name,
            "state_name": state_name,
            "start_date": start_date,
            "end_date": end_date
        },
        beforeSend: function() {
            $('.search_lead_filter_message_box').html(
                '<img src="tenor.gif" width="40" height="40"/>'
            );
        },

        success:function(data){

            console.log('data:')
            console.log(data)

            userDetails = data

            var result = $.parseJSON(data);

            console.log('result:')
            console.log(result)                       

            $("#filterRecords").empty();

            //###########################################
            // Pagination code start
            //###########################################

            $("#pagination").attr('style','display:block;');

            $('#pagination').html('<div class="row"><div class="col"><button class="col" id="PreValue"><i class="ion-skip-backward"></i> Previous</button></div>  <div id="nav-numbers" class="col nav"></div>  <div class="col"><button class="col" id="nextValue">Next <i class="ion-skip-forward"></i></button></div></div>');

            paginate_json_data(result)

             //###########################################
            // Pagination code end
            //###########################################

            $('.search_lead_filter_message_box').html('');

        }           

    });

});


});

function paginate_json_data(userDetails){

$('.search_lead_filter_message_box').html('');



userDetails = userDetails

// var table =  $('#myTable');

var table='';

table = $("<table id='myTable' style='width:30%;'></table>");

var max_size=userDetails.length;
var sta = 0;

//here if i change 3 to 10 then number of rows some navigation 3 rows display and then 10 row is displayed.

var elements_per_page = 3;


var limit = elements_per_page;

goFun(sta,limit);

function goFun(sta,limit){

    console.log(sta,limit);

    table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Linkedin</th><th>Email</th><th>Phone</th><th>State</th><th>Country</th><th>TechArea</th><th>Firm Type</th><th>Firm Size</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Description</th><th>Owner Notes</th><th>Reminder Date</th><th>Admin Notes</th><th>Lead Status</th><th>Lead Added By</th><th>Lead Added On</th><th>Lead Updated By</th><th>Lead Updated On</th></thead><br>'); 

    table.append('<tbody style="overflow-x:auto;"></tbody>'); 

    for(var i=sta;i<limit;i++){

        var tab='<tr><td>'+i+"\n"+'</td><td>'+"<a target='_blank' href=./lead/index.html?lead_id="+ userDetails[i].Lead_Id + " </a>"+userDetails[i].FirstName+' '+userDetails[i].LastName+"\n"+'</td><td>'+userDetails[i].Company+"\n"+'</td><td>'+userDetails[i].Website+"\n"+'</td><td>'+userDetails[i].Designation+"\n"+'</td><td>'+userDetails[i].Linkedin+"\n"+'</td><td>'+"<a href=mailto:" + userDetails[i].Email + ">" + userDetails[i].Email + "</a>"+"\n"+'</td><td>'+userDetails[i].Phone + "\n" +'</td><td>'+userDetails[i].State +"\n" +'</td><td>'+userDetails[i].Country +"\n" +'</td><td>'+userDetails[i].TechArea + "\n" +'</td><td>'+userDetails[i].FirmType + "\n" +'</td><td>'+userDetails[i].FirmSize + "\n" +'</td><td>'+userDetails[i].LastContactDate + "\n" +'</td><td>'+userDetails[i].NextContactDate + "\n" +'</td><td>'+userDetails[i].LeadDescription + "\n" +'</td><td>'+userDetails[i].OwnerNotes + "\n" +'</td><td>'+userDetails[i].SetReminder + "\n" +'</td><td>'+userDetails[i].AdminNotes + "\n" +'</td><td>'+userDetails[i].LeadStatus + "\n" +'</td><td>'+"<a target='_blank' href=./account/index.html?user_id="+ userDetails[i].LeadAddedBy + " </a>"+userDetails[i].LeadAddedBy + "\n" +'</td><td>'+userDetails[i].LeadAddedOn + "\n" +'</td><td>'+userDetails[i].LeadUpdatedBy + "\n" +'</td><td>'+userDetails[i].LeadUpdatedOn +"\n" +'</td></tr>';

     $('#myTable').append(tab)

    }

    $("#filterRecords").html(table);
}

$('#nextValue').click(function(){
    var next = limit;
    if(max_size>=next) {
    def = limit+elements_per_page;
    limit = def
    table.empty();
    if(limit > max_size) {
    def = max_size;
    }

    goFun(next,def);

    }
});

$('#PreValue').click(function(){
    var pre = limit-(2*elements_per_page);
    if(pre>=0) {
    limit = limit-elements_per_page;
    table.empty();
    goFun(pre,limit); 
    }
});

var number = Math.round(userDetails.length / elements_per_page);

for(i=0;i<=number;i++) {

    $('.nav').append('<button class="btn">'+i+'</button>');

}

$('.nav button').click(function(){

    var start = $(this).text();
    table.empty();
    limit = 3*(parseInt(start)+1) > max_size ? max_size: 3*(parseInt(start)+1)
    goFun(start*3,limit);

});


}


【讨论】:

  • 从您的函数paginate_json_data 中删除$(document).ready(function(){ 这部分,它可能适用于您的分页记录。对于overflow-x,请尝试在&lt;body&gt; 上应用此表。
  • 是的,这很好,但我没有水平滚动表格。你只需要一个JSON来解决分页功能的问题。我正在用 JSON 更新答案
  • 我也想使用 CSS focus 属性来知道用户是哪个页面
  • @AkhtarMunir overflow-x 不起作用,只需删除最新文件loadtable.js 中的一些代码并使用JSON数据进行纠正。
  • @AkhtarMunir 所有问题都已解决,但唯一剩下的就是这个var elements_per_page = 3; 无法正常工作,您可以通过更改值并显示结果但不正确显示行来检查它从 3 到 10 .
猜你喜欢
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 2014-10-14
  • 2016-07-27
  • 1970-01-01
  • 2021-04-16
  • 2018-02-01
相关资源
最近更新 更多