通过 Ajax / Jquery 问题的 Codeigniter 分页

Posted

技术标签:

【中文标题】通过 Ajax / Jquery 问题的 Codeigniter 分页【英文标题】:Codeigniter Pagination via Ajax / Jquery issue 【发布时间】:2020-01-26 06:03:50 【问题描述】:

所以,我有一个新的 CodeIgniter 项目,我正在努力显示一组 Fantasy Sports 分数,按周分组。如果您单独单击每个“周”,我有一个普遍的共识,但“下一页”链接不起作用,“上一页”没有按预期显示,“活动页面”没有切换。这是我目前所拥有的:

DB 小提琴https://www.db-fiddle.com/f/5Q7QezddpNEGabaia2w5FQ/0

查看

<div class="row">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Scores</h4>
            </div>
            <div class="card-body">
                <div align="right" id="pagination_link"></div>
                <div class="table-responsive" id="week_table"></div>
            </div>
        </div>
    </div>
</div>
<script>
    var league_id = "1";

    function load_league_week_scores(week, league, page) 
            $.ajax(
                url:"<?php echo base_url();?>leagues/league_scores_pagination/"+week+"/"+league+"/"+page,
                method: "GET",
                dataType: "json",
                success: function(data)
                
                    $('#week_table').html(data.week_table);
                    $('#pagination_link').html(data.pagination_link);
                
            )
        
    $(document).ready(function () 
        load_league_week_scores(1,league_id,1);
    );

    $(document).on("click", ".pagination li a", function(event) 
        event.preventDefault();
        var page = $(this).data("ci-pagination-page");
        load_league_week_scores(page, league_id, page);
    )
</script>

路线

$route['leagues/league_scores_pagination/(:num)/(:num)/(:num)'] = "leagues/league_scores_pagination/$1/$2/$3";

控制器

<?php
if (!defined('BASEPATH')) 
    exit('No direct script access allowed');


class Leagues extends CI_Controller

    private $league_id;


    function league_scores_pagination($week, $league, $page)
    
        $this->load->model('Leagues_model', 'leagues_model');
        $this->load->library('pagination');
        $this->leagues_model->setLeagueId($league);

        $num_weeks = $this->leagues_model->GetGamesCount();
        $total_rows = $num_weeks * 5;
        //https://www.youtube.com/watch?v=nfDMTzmGi9Q
        $config = array();
        $config['base_url'] = "#";
        $config["total_rows"] = $total_rows;
        $config["per_page"] = 5;
        $config["uri_segment"] = 4; // I've made changes to this nothing has fixed it.
        $config['full_tag_open']    = '<div class="paging text-center"><nav><ul class="pagination">';
        $config['full_tag_close']   = '</ul></nav></div>';
        $config['num_tag_open']     = '<li class="page-item"><span class="page-link">';
        $config['num_tag_close']    = '</span></li>';
        $config['cur_tag_open']     = '<li class="page-item active"><span class="page-link">';
        $config['cur_tag_close']    = '<span class="sr-only">(current)</span></span></li>';
        $config['next_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['next_tag_close']  = '<span aria-hidden="true"></span></span></li>';
        $config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['prev_tag_close']  = '</span></li>';
        $config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
        $config['first_tag_close'] = '</span></li>';
        $config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['last_tag_close']  = '</span></li>';
        $config["links"] = $num_weeks;
        $config["num_links"] = $num_weeks;
        $this->pagination->initialize($config);

        $output = array(
            'pagination_link' => $this->pagination->create_links(),
            'week_table' => $this->leagues_model->fetch_details($week)
        );

        echo json_encode($output);
    

型号

<?php


class Leagues_model extends CI_Model

    private $league_id;

    public function __construct()
    
        parent::__construct();
    

    public function setLeagueId($league_id)
    
        $this->league_id = $league_id;
    

    public function GetGamesCount($league_id = "")
    
        if (!empty($league_id)) 
            $this->league_id = $league_id;
        

        // Get our league count
        $league_size = $this->GetLeagueSize();

        if (empty($league_size)) 
            return false;
        

        $sql = "SELECT COUNT(nfl_user_matchups_id) as league_games FROM nfl_user_matchups WHERE leagues_id = ?";
        $query = $this->db->query($sql, $this->league_id);
        $count_leagues = $query->row()->league_games;
        $return_count = $count_leagues / $league_size;

        return $return_count;
    

    public function GetLeagueSize()
    
        if (empty($this->league_id)) 
            return false;
        
        $sql = "SELECT max_capacity FROM leagues WHERE leagues_id = ?";
        $query = $this->db->query($sql, $this->league_id);

        return $query->row()->max_capacity;
    

    public function fetch_details($week)
    
        $output = "";
        $sql = "SELECT week, home_team_id, away_team_id, my_score, their_score, a.team_name as home_team, b.team_name as away_team 
                    FROM nfl_user_matchups nm 
                        LEFT JOIN user_teams a ON nm.home_team_id = a.user_teams_id 
                        LEFT JOIN user_teams b ON nm.away_team_id = b.user_teams_id 
                    WHERE nm.week = ? AND nm.leagues_id = ? 
                    GROUP BY Greatest(home_team_id, away_team_id), Least(home_team_id, away_team_id)";

        $query = $this->db->query($sql, array($week, $this->league_id));
        $output .= '<table class="table table-bordered">';
        foreach ($query->result() as $row) 
            if($row->my_score > $row->their_score) 
                $home_bold = 'style="font-weight: bold;"';
                $away_bold = '';
             else 
                $away_bold = 'style="font-weight: bold;"';
                $home_bold = '';
            
            $output .= '<tr><td ' . $home_bold . '>' . $row->home_team . '</td>';
            $output .= '<td>' . $row->my_score . '-' . $row->their_score . '</td>';
            $output .= '<td ' . $away_bold . '>' . $row->away_team . '</td></tr>';
        
        $output .= '</table>';
        return $output;
    

正如我所说,我得到了预期的结果,但是分页 create_links() 函数无法正确填充。这是一个视频,解释了什么是有效的,什么是无效的:

https://www.screencast.com/t/7eqyatyGV

【问题讨论】:

“不起作用”和“没有正确填充”不是很有帮助。 究竟发生了什么不应该发生的事情? @Alex - 根据我的解释:'但是“下一页”链接不起作用,“上一页”没有按预期显示,“活动页面”没有切换任何一个。' @Alex - 但我确实在我的答案中添加了一个视频,以便您了解问题所在。 【参考方案1】:

要更新的内容

您在“league_scores_pagination”中进行的计算是错误的。我将结果总数传递为 5(静态和查询返回那么多)并且正在生成分页。 您也没有在模态中执行任何分页代码。 load_league_week_scores(week_id, League_id, page) -> 你在哪里通过'page'两次 var week_id = 1;自己添加的。您需要通过任何方法将其传递给控制器​​以使其动态化

更新代码

<script>
    var league_id = "1";
    var week_id = 1;

    function load_league_week_scores(week, league, page) 

            $.ajax(
                url:"<?php echo base_url();?>leagues/league_scores_pagination/"+week+"/"+league+"/"+page,
                method: "GET",
                dataType: "json",
                success: function(data)
                
                    $('#week_table').html(data.week_table);
                    $('#pagination_link').html(data.pagination_link);
                
            )
        
    $(document).ready(function () 
        load_league_week_scores(week_id,league_id,1);
    );

    $(document).on("click", ".pagination li a", function(event) 
        event.preventDefault();
        var page = $(this).data("ci-pagination-page");
        load_league_week_scores(week_id, league_id, page);
    )
</script>


    function league_scores_pagination($week, $league, $page)
    
        $per_page = 2;

        $this->load->model('Leagues_model', 'leagues_model');
        $this->load->library('pagination');
        $this->leagues_model->setLeagueId($league);

        $num_weeks = $this->leagues_model->GetGamesCount();
        $total_rows = 5;//$num_weeks * 5;
        //https://www.youtube.com/watch?v=nfDMTzmGi9Q
        $config = array();
        $config['base_url'] = "#";
        $config["total_rows"] = $total_rows;
        $config["per_page"] = $per_page;
        $config["uri_segment"] = 4; // I've made changes to this nothing has fixed it.
        $config['full_tag_open']    = '<div class="paging text-center"><nav><ul class="pagination">';
        $config['full_tag_close']   = '</ul></nav></div>';
        $config['num_tag_open']     = '<li class="page-item"><span class="page-link">';
        $config['num_tag_close']    = '</span></li>';
        $config['cur_tag_open']     = '<li class="page-item active"><span class="page-link">';
        $config['cur_tag_close']    = '<span class="sr-only">(current)</span></span></li>';
        $config['next_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['next_tag_close']  = '<span aria-hidden="true"></span></span></li>';
        $config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['prev_tag_close']  = '</span></li>';
        $config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
        $config['first_tag_close'] = '</span></li>';
        $config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
        $config['last_tag_close']  = '</span></li>';
        $config['page_query_string'] = FALSE;
        $config['use_page_numbers'] = TRUE;
        // $config["links"] = $num_weeks;
        // $config["num_links"] = $num_weeks;
        $this->pagination->initialize($config);

        $output = array(
            'pagination_link' => $this->pagination->create_links(),
            'week_table' => $this->leagues_model->fetch_details($week,$page,$total_rows,$per_page)
        );

        echo json_encode($output);
    

public function fetch_details($week, $page, $total_rows, $per_page = 10)


    $totalpages = ceil($total_rows / $per_page);

    if (isset($page) && is_numeric($page)) 
       $currentpage = (int) $page;
     else 
       $currentpage = 1;
    

    if ($currentpage > $totalpages)            
       $currentpage = $totalpages;
    

    if ($currentpage < 1) 
       $currentpage = 1;
    

    $offset = ($currentpage - 1) * $per_page;


    $output = "";
    $sql = "SELECT week, home_team_id, away_team_id, my_score, their_score, a.team_name as home_team, b.team_name as away_team 
                FROM nfl_user_matchups nm 
                    LEFT JOIN user_teams a ON nm.home_team_id = a.user_teams_id 
                    LEFT JOIN user_teams b ON nm.away_team_id = b.user_teams_id 
                WHERE nm.week = ? AND nm.leagues_id = ? 
                GROUP BY Greatest(home_team_id, away_team_id), Least(home_team_id, away_team_id) LIMIT ?, ?";

    $query = $this->db->query($sql, array($week, $this->league_id, $offset, $per_page));
    $output .= '<table class="table table-bordered">';
    foreach ($query->result() as $row) 
        if($row->my_score > $row->their_score) 
            $home_bold = 'style="font-weight: bold;"';
            $away_bold = '';
         else 
            $away_bold = 'style="font-weight: bold;"';
            $home_bold = '';
        
        $output .= '<tr><td ' . $home_bold . '>' . $row->home_team . '</td>';
        $output .= '<td>' . $row->my_score . '-' . $row->their_score . '</td>';
        $output .= '<td ' . $away_bold . '>' . $row->away_team . '</td></tr>';
    
    $output .= '</table>';
    return $output;

您可以通过调用控制器进行测试并在此处更改输入值。

http://baseurl_here/leagues/league_scores_pagination/1/1/4

【讨论】:

所以,我的所有结果都很好。问题变成导航不动。让我看看我是否可以录制并上传。此外,周和页是相同的,因为周 = 页。分页中的每个结果为 1 周(预计为 1-13)。 screencast.com/t/7eqyatyGV 另外,我尝试了您的所有更改,但它给出了相同的、不正确的、意外的行为。 league_scores_pagination/1/1/4 通过 url 访问你会得到什么结果? "pagination_link":" 1(当前) 2 3 4 5 6 7 8 9 10 11 12 13 14 下一个→ 最后 »","week_table" :"..." 你能解释一下吗?我不确定你是什么意思。我对 CI 很陌生,所以解释会有所帮助。

以上是关于通过 Ajax / Jquery 问题的 Codeigniter 分页的主要内容,如果未能解决你的问题,请参考以下文章

通过jQuery Ajax提交表单数据时同时上传附件

禁用 Jquery Mobile Ajax 导航

使用 jQuery AJAX 发送多个数据参数

带有 AJAX 的 JQuery 需要用多维数组创建手风琴

终于掉坑里了!!!vue-resource和jquery的ajax不一样

jQuery - Servlet 的 AJAX 调用