簡體   English   中英

如何在此 Codeigniter 應用程序中通過 jQuery Ajax 加載特定數據,而不是整個頁面?

[英]How do I load specific data via jQuery Ajax in this Codeigniter application, instead of the entire page?

我一直在使用CodeIgniter 3.1.8和 Twitter Bootstrap 4 開發在線報紙/博客應用程序。我目前正在研究延遲加載(帖子)功能。

默認情況下,帖子分頁並一次顯示12 個,在http://myblog.com/http://myblog.com/?page=2等。

application\\controllers\\Posts.php我有

private function _initPagination($path, $totalRows, $query_string_segment = 'page')
{
    //load and configure pagination 
    $this->load->library('pagination');
    $config['base_url']             = base_url($path);
    $config['query_string_segment'] = $query_string_segment;
    $config['enable_query_strings'] = TRUE;
    $config['reuse_query_string']   = TRUE;
    $config['total_rows']           = $totalRows;
    $config['per_page']             = 12;

    if($this->Static_model->get_static_data()['has_pager']){
        $config['display_pages'] = FALSE;
        $config['first_link'] = FALSE;
        $config['last_link'] = FALSE;
        $config['prev_tag_open'] = '<li class="prev">';
        $config['prev_tag_close'] = '</li>';
        $config['next_tag_open'] = '<li class="next">';
        $config['next_tag_close'] = '</li>';
    }

    if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
        $_GET[$config['query_string_segment']] = 1;
    }
    $this->pagination->initialize($config);
    
    $limit  = $config['per_page'];
    $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;
    
    return array(
        'limit' => $limit,
        'offset' => $offset
    );
}

public function index()
{
    //call initialization method
    $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());
    $data                  = $this->Static_model->get_static_data();
    $data['base_url']      = base_url("/");
    $data['pages']         = $this->Pages_model->get_pages();
    $data['categories']    = $this->Categories_model->get_categories();
    $data['search_errors'] = validation_errors();
    
    //use limit and offset returned by _initPaginator method
    $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
    $this->twig->addGlobal('pagination', $this->pagination->create_links());
    
    // featured posts
    if ($data['is_featured']) {
        $data['featured'] = $this->Posts_model->featured_posts();
        $this->twig->addGlobal('featuredPosts', "themes/{$data['theme_directory']}/partials/hero.twig");
    }
    
    $this->twig->display("themes/{$data['theme_directory']}/layout", $data);
} 

為了通過 jQuery Ajax 加載帖子,我有:

(function($) {

    var currentPage = 1;

    // Hide pahination
    $('.pagination').hide();

    $(window).scroll(function() {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
            loadMore();
        }
    });

    function loadMore() {
        $.ajax({
                url: baseUrl + '?page=' + currentPage,
                type: 'POST',
                beforeSend: function() {
                    $('.loader').show();
                }
            })
            .done(function(data) {
                $('.loader').hide();
                // Append new posts to the posta container
                $("#postsContainer").append(data);
                currentPage = currentPage + 1;
            });
    }

})(jQuery);

HTML

<div class="col-lg-8 col-md-10 mx-auto" id="postsContainer">
  <div class="post-preview">
    <a href="http://myblog.com/learn-to-code-with-us-for-a-better-future">
      <h2 class="post-title">Learn to code with us, for a better future</h2>
      <h3 class="post-subtitle">Learn to code with us. We have the best teachers in the country.</h3>
    </a>
    <p class="post-meta">
      Posted in <a href="http://myblog.com/categories/posts/1" title="All posts in Uncategorized">Uncategorized</a>, on Nov 19, 2019
    </p>
  </div>
  <hr>
  ...
</div>

問題

由於我無法弄清楚的原因,當我滾動到頁面底部時,不是將帖子附加到帖子容器,而是附加整個頁面

我的錯誤在哪里?

您似乎正在嘗試使用分頁數據重新加載整個頁面 - 這是一個非常糟糕的做法。 從長遠來看,您最終會以這種方式獲得較慢的頁面。

您最好為 AJAX 設置一個單獨的端點,該端點輸出 HTML 字符串的 JSON 數組,每個帖子一個。 這仍然比使用像 Codeigniter 和 React 這樣的 2 層解決方案慢,但肯定比不斷重新渲染整個 UI 快。

我得到了一個有效的解決方案:

(function($) {

    var currentPage = 2,
        maxPage = $('#postsContainer').data('max-page'),
        posts = null;

    $('.pagination').hide();

    $(window).scroll(function() {
        var toBottom = $(window).scrollTop() >= $(document).height() - $(window).height() - 25;

        if (toBottom && currentPage <= maxPage) {
            loadMore();
        }
    });

    function loadMore() {
        $.ajax({
                url: baseUrl + '?page=' + currentPage,
                type: 'GET',
                beforeSend: function() {
                    if (typeof posts != 'undefined') {
                        $('.loader').show();
                    }
                }
            })
            .done(function(data) {
                $('.loader').hide();
                posts = $(data).find('#postsContainer').html();

                if (typeof posts != 'undefined') {
                    $('#postsContainer').append(posts);
                    currentPage = currentPage + 1;

                    if (currentPage > maxPage) {
                        $('#postsContainer').append('<p class="text-center text-muted">No more posts to load</p>');
                    }
                }
            });
    }

})(jQuery);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM