首页 > 解决方案 > 使用选择 2 ajax 远程数据对结果进行分页

问题描述

尝试使用 Select2 (v 4.0.6.rc1) 对 ajax 数据进行分页,以便用户可以找到更多结果(如果第一个限制中不存在),使用以下但不检索数据。如果有人帮助我,我将不胜感激关于分页的例子不多。

我试图在这个问题Select2 v4 how to paginate results using AJAX的帮助下对数据进行分页,它似乎不起作用,获取数组但格式不正确。

JS:

  $('#compose_username').select2({
        dropdownParent: $("#modal-compose") ,
        placeholder: "Search Username...",
        minimumInputLength: 1,
        ajax: {
            url: "username.php",
            dataType: 'json',
            delay: 250,
            cache: false,
            data: function (params) {
                return {
                    term: params.term,
                    page: params.page || 1                      
                    //a: params.term, // search term
                    //psf: params.page
                };
            },
            processResults: function(data) {
                console.log(data);
                var result = $.map(data, function (item) { return { id: item.id, text: item.username }});
                return { results: result };
            }
        }
  });

PHP

    try{
         $page= $_GET['page'];
        // $resultCount = 10;
        // $offset = ($page - 1) * $resultCount;
  $pageLength = 20;
  $pageStart = ($page - 1) * $pageLength;
  $pageEnd = $pageStart + $pageLength;  

        $stmt = $db_con->query("SELECT id,first_name FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}");
        $count = $db_con->query("SELECT count(first_name) FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}")->fetchColumn();;
        $stmt->execute();
            $json = [];
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                 $json[] = ['id'=>$row['id'], 'username'=>$row['first_name']];
            }
    $endCount = $pageStart + $pageLength;
    $morePages = $endCount > $count;            
$results = array(
  "results" => $json,
  "pagination" => array(
    "more" => $morePages
  )
);          
            echo json_encode($results);
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }

标签: phpjsonajaxpaginationjquery-select2

解决方案


没有找到太多关于 select2 paginate 的例子,我必须自己弄清楚,这里是如何使用 Select2 对数据进行分页(无限滚动)的完整工作:希望这对其他人有帮助。

JS:

$('#compose_username').select2({
    dropdownParent: $("#modal-compose") ,
    placeholder: "Search Username...",
    minimumInputLength: 1,
    allowClear: true,
    ajax: {
        url: "username.php",
        dataType: 'json',
        delay: 250,
        cache: false,
        data: function (params) {
            return {
                term: params.term,
                page: params.page || 1,
            };
        },
        processResults: function(data, params) {
            //console.log(data);
            //  NO NEED TO PARSE DATA `processResults` automatically parse it
            //var c = JSON.parse(data);
            console.log(data);
            var page = params.page || 1;
            return {
                results: $.map(data, function (item) { return {id: item.col, text: item.col}}),
                pagination: {
                // THE `10` SHOULD BE SAME AS `$resultCount FROM PHP, it is the number of records to fetch from table` 
                    more: (page * 10) <= data[0].total_count
                }
            };
        },              
    }
});

PHP(使用 PDO):

try{
    $page= $_GET['page'];
    $resultCount = 10;
    $end = ($page - 1) * $resultCount;       
    $start = $end + $resultCount;

    $stmt = $db_con->query("SELECT col,col FROM table WHERE col LIKE '".$_GET['term']."%' LIMIT {$end},{$start}");
    $stmt->execute();
    $count = $stmt->rowCount();
    $data = [];
    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
        $data[] = ['id'=>$row['id'], 'col'=>$row['col'],'total_count'=>$count];
        
    // IF SEARCH TERM IS NOT FOUND DATA WILL BE EMPTY SO
    if (empty($data)){
        $empty[] = ['id'=>'', 'col'=>'', 'total_count'=>'']; 
        echo json_encode($empty);
    }

    else 
        echo json_encode($data);
        
}
catch(PDOException $e){
    echo $e->getMessage();
}

推荐阅读