使用选择的2个ajax远程数据进行分页结果

时间:2018-08-30 23:13:31

标签: php json ajax pagination jquery-select2

尝试使用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();
    }

1 个答案:

答案 0 :(得分:0)

没有找到很多有关select2分页的示例,不得不靠我自己弄清楚,这是如何使用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();
}