Codeigniter Pagination через выпуск Ajax / Jquery - PullRequest
0 голосов
/ 26 сентября 2019

Итак, у меня есть новый проект CodeIgniter, и я работаю над отображением коллекции результатов Fantasy Sports, сгруппированных по неделям.У меня общий консенсус работает, если вы нажимаете каждую «неделю» по отдельности, но ссылка «Следующая страница» не работает, а «Предыдущая страница» не отображается должным образом, а «активная страница» не работаетПереключи либо.Вот что у меня есть:

DB Fiddle 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

1 Ответ

1 голос
/ 26 сентября 2019

Что нужно обновить

  • Неправильные расчеты, которые вы выполняете в league_scores_pagination.Я передал общее число результатов как 5 (статическое и запрос возвращает столько), и пагинация генерируется.
  • Вы не делаете никакой код нумерации страниц в вашем модале тоже.
  • load_league_week_scores (week_id, league_id, 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...