ajax MySQL PHP 实现无刷新更新列表
在学ajax时我们要会去看谷歌控制台的network,注意看页面每次请求的参数。last的值是每次+3,而,comment一直是3.。这样是符合我的思路的
data.php
<?php require_once(‘../mysql/cont.php‘); $last = $_GET[‘last‘]; $amount = $_GET[‘amount‘]; $query=mysqli_query($conn,"select * from comment order by id desc limit $last,$amount"); $flag = false; while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){ $flag = true; $sayList[] = array( ‘id‘=>$row[‘id‘], ‘nickname‘=>$row[‘nickname‘], ‘content‘=>$row[‘content‘], ‘imgpath‘=>$row[‘imgpath‘], ‘time‘=>$row[‘time‘] ); } if($flag){ echo json_encode($sayList); }else{ echo true;//当SQL查询不到数据时,输出1 PHP的true相当于1,false相当于0 } ?>
html 页面
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>评论动态加载</title> <style type="text/css"> .comment{ background: #FFF; #border-bottom: red solid; width: 600px; height: 80px; } .comment div img{ width: 80px; height: 80px; } .left{ float: left; width: 80px; height: 80px; background: blue; } .right{ float: right; width: 520px; height: 80px; } #container{ position: relative; left: 50%; width: 600px; margin-left: -300px; } #container ul{ padding-left: 0px; list-style: none; } #more{ background: lightGray; height: 30px; line-height: 30px; text-align: center; cursor: pointer; } </style> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> </head> <body> <div style="height:100px;width: 600px;background-color: #90EE90;margin: 0 auto; text-align: center;line-height: 100px;"> 我是轮播图 </div> <div id="container"> <ul id="contentList"> </ul> <div id="more">加载更多...<input type="hidden" id="last" value="0"></div> </div> <script type="text/javascript"> $(function(){ var index=3;//全局变量,每次请求数据的条数 // 刚加载时,执行一次ajax请求 var last = $(‘#last‘).val(); queryComment(last,index); $(‘#more‘).click(function(){ // 当点击是获得隐藏域的value值 var last = $(‘#last‘).val(); // 请求一次ajax queryComment(last,index); }); }); function queryComment(last,index){ $.ajax({ type : "get", async: true, url : "data.php",//服务器页面 data:{last:last,amount:index},//传给服务器的url参数 dataType : "json",//传过来数据的类型 success : function(data){ if(data == 1){//当服务器传过来的数据为1时,修改文本内容,并解除绑定 $(‘#more‘).html(‘没有更多评论!‘).unbind(‘click‘); return false;//跳出函数不再执行 } $.each(data,function(i,element){ var nickname = element.nickname; var content = element.content; var time = element.time; var imgpath = element.imgpath; var str=‘<li class="comment">‘+ ‘<div class="left"><img src="‘+imgpath+‘"></div>‘+ ‘<div class="right"><div>‘+nickname+‘</div>‘+‘<div>‘+time+‘</div>‘+content+‘</div></li><hr>‘ var $info = $(str); $(‘#contentList‘).append($info);//把内容追加到contentlist的末尾 }); var now = parseInt($(‘#last‘).val()) + index;//将隐藏域的value加上要更新的条数 $(‘#last‘).val(now);//改变隐藏域value值 }, error:function(){ console.log(‘fail‘); } }); } </script> </body> </html>
数据库和连接数据库php https://www.cnblogs.com/shangrao/p/12880118.html