tp5做無刷新分頁

thinkPHP5無刷新分頁

  1. php控制器判斷是否爲ajax請求
//分頁變量
$page=$articles->render();
$this->assign('page',$page);
//文章變量
$this->assign('articles', $articles);
//判斷ajax請求,渲染到不同模板
if(request()->isAjax()){
    //return $articles;
    //如果是ajax請求,則渲染到該頁面
    return $this->fetch('articleList');
}
else {
    //否則到該頁面
    return $this->fetch('articleIndex');
}

  1. 負責ajax請求渲染的模板
<!-- START TABLE -->
<div class="simplebox grid740">

    <div class="titleh">
        <h3>博文列表</h3>
    </div>

    <table id="myTable" class="tablesorter">
        <thead>
        <tr>
            <th>#ID</th>
            <th>作者</th>
            <th>分類</th>
            <th>標題</th>
            <th>發佈日期</th>
            <th>評論數量</th>
            <th>狀態</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        {volist name='articles' id='article' key="k"}
        <tr>
            <td>{$k}</td>
            <td>作者</td>
            <td>{$article.c_name}</td>
            <td>{$article.name}</td>
            <td>{$article.publishtime|date="y-m-d",###}</td>
            <td>{$article.id|count}</td>
            <td>{$article.status}</td>
            <td>
                <form action="\article\{$article.id}\edit" name="edit">
                    <button>編輯</button>
                </form>
                <form action="\article\{$article.id}" name="delete" method="post">
                    <button onclick="return confirm('是否確定刪除文章:{$article.c_name}?');">刪除</button>
                    <input type="hidden" name="_method" value="DELETE">
                </form>
            </td>
        </tr>
        {/volist}
        </tbody>
    </table>
    {$page}
</div>
<!-- END TABLE -->
  1. 正式訪問頁面執行ajax請求
{literal}
<script>
    $(function () {
    //idlist的元素代理綁定下面所有的a元素"click"事件
        $("#list").on("click",".pagination a",function() {
        //a標籤的hrefurl發送ajax請求
        $.get($(this).attr('href'),function(html){
        //返回數據輸出到idlist的元素中
                $('#list').html(html);
            });
            //阻止默認事件和冒泡,即禁止跳轉
            return false;
        })
    })
</script>
{/literal}
<div id="list">
    <!-- START TABLE -->
    <div class="simplebox grid740">

        <div class="titleh">

發佈了44 篇原創文章 · 獲贊 14 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章