基于ajax实现点击加载更多无刷新载入到本页
程序员文章站
2022-06-09 09:22:50
先给大家展示效果图:
本例是分页的另外一种显示方式,并不是隐藏未显示的内容
数据库结构与《ajax 翻页》是一样的
javascript 代码...
先给大家展示效果图:
本例是分页的另外一种显示方式,并不是隐藏未显示的内容
数据库结构与《ajax 翻页》是一样的
javascript 代码
<script type="text/javascript"> $(document).ready(function() { var track_click = ; //track user click on "load more" button, righ now it is click var total_pages = <?php echo $total_pages; ?>; $('#results').load("fetch_pages.php", {'page':track_click}, function() {track_click++;}); //initial data to load $(".load_more").click(function (e) { //user clicks on button $(this).hide(); //hide load more button on click $('.animation_image').show(); //show loading image if(track_click <= total_pages) //make sure user clicks are still less than total pages { //post page number and load returned data into result element $.post('fetch_pages.php',{'page': track_click}, function(data) { $(".load_more").show(); //bring back load more button $("#results").append(data); //append data received from server //scroll page to button element $("html, body").animate({scrolltop: $("#load_more_button").offset().top}, ); //hide loading image $('.animation_image').hide(); //hide loading image once data is received track_click++; //user click increment on load button }).fail(function(xhr, ajaxoptions, thrownerror) { alert(thrownerror); //alert any http error $(".load_more").show(); //bring back load more button $('.animation_image').hide(); //hide loading image once data is received }); if(track_click >= total_pages-) { //reached end of the page yet? disable load button $(".load_more").attr("disabled", "disabled"); } } }); }); </script>
xml/html代码
<div id="results"></div> <div align="center"> <button class="load_more" id="load_more_button">load more</button> <div class="animation_image" style="display:none;"><img src="ajax-loader.gif"> loading...</div> </div>
fetch_pages.php
php代码
<?php include("conn.php"); $item_per_page = 3; //sanitize post value $page_number = filter_var($_post["page"], filter_sanitize_number_int, filter_flag_strip_high); //throw http error if page number is not valid if(!is_numeric($page_number)){ header('http/1.1 500 invalid page number!'); exit(); } //get current starting point of records $position = ($page_number * $item_per_page); //limit our results within a specified range. $results = mysql_query("select * from content order by id desc limit $position, $item_per_page"); //output results from database echo '<ul class="page_result">'; while($row = mysql_fetch_array($results)) { echo '<li id="item_'.$row["id"].'"><span class="page_name">'.$row["id"].') '.$row["name"].'</span><span class="page_message">'.$row["message"].'</span></li>'; } echo '</ul>'; ?>
以上内容是小编给大家介绍的基于ajax实现点击加载更多无刷新载入到本页,希望大家喜欢。
下一篇: 详解JAVA中接口的定义和接口的实现