php_ajax点击加载更多demo演示

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>php_ajax点击加载更多Demo演示</title>
</head>
<script src="jquery-1.8.0.min.js"></script>
<script>
    $(function () {
        //初始化加载数据
        ajaxSend(0);
        var index = 1;
        $("#more").click(function () {
            ajaxSend(index);
            index = index + 1;
        });
    });
    //ajax交互函数
    function ajaxSend(pageIndex) {
        $.ajax({
            type: "POST",
            url: "test.php",
            data: {pageIndex: pageIndex}, //传递参数,作为后台返回页码的依据
            dataType: "json",   //返回的数据为json
            beforeSend: function () {
                $("#more").text("正在加载中...");
            },
            //成功获取数据后,返回的是json二位数组
            success: function (msg) {
                $("#more").text("加载更多...");
                //获取返回的总页数,进行到达最大页判断
                var totalPage = msg.totalPage;
                var list = msg.list;   //json中的list是一个数组
                var tpl = "";
                //遍历list数组,index是下标0,1..,array是这个下标对应的键值
                $.each(list, function (index, content) {
                    tpl += "<li class='question'>" + content['content'] + 

"</li>" +
                    "<li class='answer'>" + content['addtime'] + "</li>";
                });
                $("#list").append(tpl);
                //判断是否到达最要页数
                if (index >= totalPage) {
                    $("#more").text("没有了").css("background", 

"#555").unbind("click");//取消绑定click事件
                }
            },
            error: function () {
                alert("加载错误");
            }
        });
    }
</script>
<body>
<div id="list">

</div>
<a href="javascript:;" id="more">加载更多</a>
</body>
</html>

php处理程序:

<?php
include_once('conn.php');

//接收前台发送的分页数据
$page = intval($_POST['pageIndex']);

//获取总记录数
$result = mysql_query("select * from say");
$total = mysql_num_rows($result);

$pageSize = 3; //每页显示数
$totalPage = ceil($total / $pageSize); //总页数
$startPage = $page * $pageSize; //开始页数

$arr['totalPage'] = $totalPage;

$res = mysql_query("select * from say order by userid asc limit $startPage , $pageSize");

while ($row = mysql_fetch_array($res)) {//获取所有数据行
    $arr['list'][] = array(
        'id' => $row['userid'],//把行中id字段的值赋值给id
        'content' => $row['content'],
        'addtime' => $row['addtime'],
    );
}
//转为为json格式,这里输出的字符格式与前台无关
echo json_encode($arr);

?>
<?php
/**
 * @authors miniamin
 * @date 2014-03-17 13:38:22
 * @version 1.0
 */
$host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "test";
$link = mysql_connect($host, $db_user, $db_pass);
$sql = mysql_select_db($db_name, $link);
mysql_query('SET NAMES UTF8');

?>
conn.php数据库配置

 

posted on 2016-03-20 22:04  gimin  阅读(1569)  评论(0)    收藏  举报