实现的效果:实现类似加载更多的效果
实现思路:
- 触发事件
- 发起ajax请求(要传递什么参数)
- 后端PHP业务逻辑的处理
- 回显(图片和文字或者评论信息)
example.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<?php $pdo = new PDO('mysql:host=127.0.0.1:8889;dbname=ajax_test','root','root'); $res = $pdo->query("SELECT `name`,`price` FROM `test1` limit 0,3"); $arr = $res->fetchAll(PDO::FETCH_ASSOC); ?> <!doctype html> <html> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8'> <!--加载jquery.js--> <script src='http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js'></script> </head> <body> <table align='center' border='1'> <tr> <th>名字</th> <th>价格</th> </tr> <?php foreach($arr as $k=>$v){ echo "<tr>"; echo '<td>'.$v['name'].'</td><td>'.$v['price'].'</td>'; echo "</tr>"; } ?> </table> <center><button id='bid' >加载更多</button></center> <script> //1.触发事件 $('#bid').click(function(){ var num = $('tr').length - 1 ; $.post('./test7.php',{number:num},function(data){ //2.ajax请求 if(data.code == 200){ //正常返回数据 $('table').append(data.msg); } if(data.code == 400){ alert('对不起,已超过最大数量'); } if(data.code == 300){ $('table').append(data.msg); alert('数据已取完'); $('#bid').remove(); } /*1. 页面已有10条记录 加载10-20记录 2. 页面已有20条记录 加载20-30记录 3. 页面已有50条记录 加载50-60记录 4. 页面已有n条记录 加载n-(n+10)记录 前提:数据要有足够的记录 假如数据库只有16条记录 6条 data 1:当前页面显示了多少条记录*/ },'json'); }); </script> </body> </html> |
test7.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php //实例化Pdo $pdo = new PDO('mysql:host=127.0.0.1:8889;dbname=ajax_test','root','root'); $num = isset($_POST['number']) ? (int)$_POST['number'] : 3; //1.判断当前页面的数量是否已经超过总数量 $arr = $pdo->query('SELECT COUNT(*) AS count FROM test1'); $res = $arr->fetch(PDO::FETCH_ASSOC); if($num > $res['count']){ die(json_encode(array('msg'=>'超过最大数量','code'=>400))); } if($num == $res['count']){ die(json_encode(array('msg'=>'对不起数据已被取完','code'=>300))); } if($num < $res['count']){ $sql = $pdo->query('SELECT `name`,`price` FROM `test1` LIMIT '.$num.',3'); $result = $sql->fetchAll(PDO::FETCH_ASSOC); $msg = ''; foreach($result as $k=>$v){ $msg .= '<tr><td>'.$v['name'].'</td><td>'.$v['price'].'</td></tr>'; } if($res['count']>=$num+3){ //剩余数据大于3条 die(json_encode(array('msg'=>$msg,'code'=>200))); }else{ //剩余数据不足3条 die(json_encode(array('msg'=>$msg,'code'=>300))); } } |