Typecho 实现首页循环加载的一种思路
No Reply , Posted in 代码 on October 10, 2015
在制作模板的时候需要实现首页无限加载的功能,大概就是在第一页点击加载更多然后将第一页和第二页结合显示。
这里简单讨论下思路。
假如皮肤文件index.php中的代码如下:
<html> <head> <!--- 省略head代码 ---> </head> <body> <div id="post_list_containner"> <?php while($this->next():)?> <section class="article_section"> <h2><?php $this->title() ?></h2> <div><?php $this->excerpt(200);?></div> </section> <?php endwhile?> </div> </body> </html>
注意:本文所有代码仅作演示,用于说明实现思路,并没有实际调试过。
首先,增加js代码,当页面滚动到最后,或者点击按钮“加载更多”时,ajax方式加载新文章列表。
<html> <head> <!--- 省略head代码 ---> </head> <body> <div id="post_list_containner"> <?php while($this->next():)?> <section class="article_section"> <h2><?php $this->title() ?></h2> <div><?php $this->excerpt(200);?></div> </section> <?php endwhile?> </div> <div id="load_more"> <button class="load_more_button" onclick ="load_more_post()">加载更多</button> </div> </body> <script> var current_page = 1; function load_more_post(){ current_page ++; var load_post_url = window.location.href + "/page/" + current_page + "/?load_type=ajax"; $.get(load_post_url,function(html){ $('#post_list_container').append($(html)); }) } </script> </html>
代码说明:点击“加载更多”按钮时,调用
load_more_post
函数,并加载下一页的文章内容。注意加载的url中加了一个load_type=ajax
参数,用于标示该请求是ajax方式加载。
然后,继续修改index.php皮肤文件,增加如下代码:
<?php if(isset($_GET['load_type']) and $_GET['load_type'] == 'ajax'): ?> <?php while($this->next():)?> <section class="article_section"> <h2><?php $this->title() ?></h2> <div><?php $this->excerpt(200);?></div> </section> <?php endwhile?> <?php return; //完成ajax方式返回,退出此页面?> <?php endif ?>
汇总index.php代码如下:
<?php //这一段,ajax方式加载文章列表 ?> <?php if(isset($_GET['load_type']) and $_GET['load_type'] == 'ajax'): ?> <?php while($this->next():)?> <section class="article_section"> <h2><?php $this->title() ?></h2> <div><?php $this->excerpt(200);?></div> </section> <?php endwhile?> <?php return; //完成ajax方式返回,退出此页面?> <?php endif ?> <?php //这一段开始,正常的首页输出 ?> <html> <head> <!--- 省略head代码 ---> </head> <body> <div id="post_list_containner"> <?php while($this->next():)?> <section class="article_section"> <h2><?php $this->title() ?></h2> <div><?php $this->excerpt(200);?></div> </section> <?php endwhile?> </div> <div id="load_more"> <button class="load_more_button" onclick ="load_more_post()">加载更多</button> </div> </body> <script> var current_page = 1; function load_more_post(){ current_page ++; var load_post_url = window.location.href + "/page/" + current_page + "/"; $.get(load_post_url,function(html){ $('#post_list_container').append($(html)); }) } </script> </html>