>  기사  >  PHP 프레임워크  >  thinkphp에서 일부 콘텐츠의 ajax 비새로고침 페이징에 대한 자세한 설명

thinkphp에서 일부 콘텐츠의 ajax 비새로고침 페이징에 대한 자세한 설명

藏色散人
藏色散人앞으로
2022-01-31 05:00:302173검색

다음 thinkphp 프레임워크 튜토리얼 칼럼에서는 thinkphp 아래의 페이지 콘텐츠 일부에 대한 ajax 비새로고침 페이징을 소개합니다. 이 내용이 필요한 친구들에게 도움이 되길 바랍니다!

thinkphp 프레임워크와 함께 제공되는 페이지 일부의 Ajax 새로 고침이 아닌 페이징은 페이지를 넘길 때마다 전체 페이지를 새로 고쳐야 합니다. 이런 종류의 페이지 넘기기 사용자 경험은 분명히 아닙니다. 이상적으로는 페이지를 넘길 때마다 원하는 데이터 세트 부분의 데이터만 새로 고치기를 바랍니다. 이러한 방식으로 ajax를 사용하여 데이터베이스와 비동기식으로 상호 작용하는 Ajax 비동기 통신을 쉽게 생각할 수 있습니다. 개발 과정에서 mysql 데이터베이스를 사용하고, 데이터베이스에서 데이터를 가져오며, 쿼리된 데이터가 반환되고 원본 데이터가 jquery로 대체되므로 페이지를 새로 고치지 않고도 부분 새로 고침을 수행할 수 있습니다. 원하는 효과.
thinkphp ajax 페이징 클래스
이 페이징 클래스는 온라인에서 찾을 수 있는 리소스입니다. 내 클래스 이름은 AjaxPage.class.php입니다. 필요한 경우 네임스페이스를 수정할 수 있습니다

1f87a0dc59f026a747ee557226eb4900'条记录','prev'=>'上一页','next'=>'下一页','first'=>'第一页','last'=>'最后一页','theme'=>' %totalRow% %header% %nowPage%/%totalPage% 页 %upPage% %downPage% %first%  %prePage%  %linkPage%  %nextPage% %end%');
// 默认分页变量名
protected $varPage;


public function __construct($totalRows,$listRows='',$ajax_func,$parameter='') {
    $this->totalRows = $totalRows;
    $this->ajax_func = $ajax_func;
    $this->parameter = $parameter;
    $this->varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p' ;
    if(!empty($listRows)) {
        $this->listRows = intval($listRows);
    }
    $this->totalPages = ceil($this->totalRows/$this->listRows);     //总页数
    $this->coolPages  = ceil($this->totalPages/$this->rollPage);
    $this->nowPage  = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
    if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
        $this->nowPage = $this->totalPages;
    }
    $this->firstRow = $this->listRows*($this->nowPage-1);
}

 public function nowpage($totalRows,$listRows='',$ajax_func,$parameter='') {
    $this->totalRows = $totalRows;
    $this->ajax_func = $ajax_func;
    $this->parameter = $parameter;
    $this->varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p' ;
    if(!empty($listRows)) {
        $this->listRows = intval($listRows);
    }
    $this->totalPages = ceil($this->totalRows/$this->listRows);     //总页数
    $this->coolPages  = ceil($this->totalPages/$this->rollPage);
    $this->nowPage  = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
    if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
        $this->nowPage = $this->totalPages;
    }
    $this->firstRow = $this->listRows*($this->nowPage-1);

    return $this->nowPage;
}

public function setConfig($name,$value) {
    if(isset($this->config[$name])) {
        $this->config[$name]    =   $value;
    }
}

public function show() {
    if(0 == $this->totalRows) return '';
    $p = $this->varPage;
    $nowCoolPage      = ceil($this->nowPage/$this->rollPage);
    $url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?").$this->parameter;
    $parse = parse_url($url);
    if(isset($parse['query'])) {
        parse_str($parse['query'],$params);
        unset($params[$p]);
        $url   =  $parse['path'].'?'.http_build_query($params);
    }
    //上下翻页字符串
    $upRow   = $this->nowPage-1;
    $downRow = $this->nowPage+1;
    if ($upRow>0){
        $upPage="4c6ddcfa986b1cfd4b100c516dd444ceajax_func."(".$upRow.")'>".$this->config['prev']."5db79b134e9f6b82c0b36e0489ee08ed";
    }else{
        $upPage="";
    }

    if ($downRow 8aa9cd03f13872f1c27a1dd7dc85aa49totalPages){
        $downPage="4c6ddcfa986b1cfd4b100c516dd444ceajax_func."(".$downRow.")'>".$this->config['next']."5db79b134e9f6b82c0b36e0489ee08ed";
    }else{
        $downPage="";
    }
    // 5e91ac722550d2d65fc65c3024cfc1f6 >>
    if($nowCoolPage == 1){
        $theFirst = "";
        $prePage = "";
    }else{
        $preRow =  $this->nowPage-$this->rollPage;
        $prePage = "4c6ddcfa986b1cfd4b100c516dd444ceajax_func."(".$preRow.")'>上".$this->rollPage."页5db79b134e9f6b82c0b36e0489ee08ed";
        $theFirst = "4c6ddcfa986b1cfd4b100c516dd444ceajax_func."(1)' >".$this->config['first']."5db79b134e9f6b82c0b36e0489ee08ed";
    }
    if($nowCoolPage == $this->coolPages){
        $nextPage = "";
        $theEnd="";
    }else{
        $nextRow = $this->nowPage+$this->rollPage;
        $theEndRow = $this->totalPages;
        $nextPage = "4c6ddcfa986b1cfd4b100c516dd444ceajax_func."(".$nextRow.")' >下".$this->rollPage."页5db79b134e9f6b82c0b36e0489ee08ed";
        $theEnd = "4c6ddcfa986b1cfd4b100c516dd444ceajax_func."(".$theEndRow.")' >".$this->config['last']."5db79b134e9f6b82c0b36e0489ee08ed";
    }
    // 1 2 3 4 5
    $linkPage = "";
    for($i=1;$i930cdc47afbfa294d5d6bff505cbe3ddrollPage;$i++){
        $page=($nowCoolPage-1)*$this->rollPage+$i;
        if($page!=$this->nowPage){
            if($page930cdc47afbfa294d5d6bff505cbe3ddtotalPages){
               $linkPage .= " 4c6ddcfa986b1cfd4b100c516dd444ceajax_func."(".$page.")'> ".$page." 5db79b134e9f6b82c0b36e0489ee08ed";
            }else{
                break;
            }
        }else{
            if($this->totalPages != 1){
                $linkPage .= " c9c3467744b1ee299b813ab65906400d".$page."54bdf357c58b8a65c66d7c19c8e4d114";
            }
        }
    }
    $pageStr  =  str_replace(
        array('%header%','%nowPage%','%totalRow%','%totalPage%','%upPage%','%downPage%','%first%','%prePage%','%linkPage%','%nextPage%','%end%'),
        array($this->config['header'],$this->nowPage,$this->totalRows,$this->totalPages,$upPage,$downPage,$theFirst,$prePage,$linkPage,$nextPage,$theEnd),$this->config['theme']);
    return $pageStr;
}

}
.

특정 단계
1. Controller
이제 index 메소드에 표시되고, page 메소드에 fetch 및 ajaxReturn이 표시됩니다. 여기서 fetch는 참조 페이지(article)

cd43c1cac171b9d5901cb44c2adcb334count();
        //实例化分页类,传入三个参数,分别是数据总数、每页显示的数据条数、要调用的jQuery ajax方法名
        $p=new \Think\AjaxPage($count,4,'server');
        //产生分页信息
        $page=$p->show();
        //要查询的数据,limit表示每页查询的数量,这里为4条
        $data = $info->limit($p->firstRow.','.$p->listRows)->select();
        //assign方法往模板赋值
        $this->assign('list',$data);
        $this->assign('page',$page);
//        $res["content"] = $this->fetch('Index/index');
//        $this->ajaxReturn($res);
        $this->display();
    }
    public function page(){
        //实例化数据模型
        $info=M('info');
        //统计要查询数据的数量
        $count=$info->count();
        //实例化分页类,传入三个参数,分别是数据总数、每页显示的数据条数、要调用的jQuery ajax方法名
        $p=new \Think\AjaxPage($count,4,'server');
        //产生分页信息
        $page=$p->show();
        //要查询的数据,limit表示每页查询的数量,这里为4条
        $data = $info->limit($p->firstRow.','.$p->listRows)->select();
        //assign方法往模板赋值
        $this->assign('list',$data);
        $this->assign('page',$page);
        //ajax返回信息
        $res["content"] = $this->fetch('Index/article');
        $this->ajaxReturn($res);
    }
}

2.Column 템플릿 인덱스입니다. html

그 중 참조된 템플릿은 페이지를 만들어야 하는 콘텐츠의 일부입니다

76c82f278ac045591c9159d381de2c57
100db36a723c770d327fc0aef2ce13b1
93f0f5c25f18dab9d176bd4f6de5d30e
9c3bca370b5104690d9ef395f2c5f8d1
e388a4556c0f65e1904146cc1a846bee
    hello world
94b3e26ee717c64999d7867364b1b4a3
4826afc8bc0934c5141d6810ee82aa53
3f1c4e4b6b16bbbd69b2ee476dc4f83a
    function server(pid){  
        var pid = pid;
        $.get("{:U('Index/page')}", "p="+pid, function(data){  
             $("#server").replaceWith("7db81b6f8cec3ce3f482d60b8ae1b72c"
             +data.content+
             "94b3e26ee717c64999d7867364b1b4a3"); 
        });
    }
2cacc6d41bbb37262a98f745aa00fbf0 
6432ecebf4dfccad7c9cdaa663a4dfcc2cacc6d41bbb37262a98f745aa00fbf0
73a6ac4ed44ffec12cee46588e518a5e
페이지를 만들어야 하는 템플릿

article.html

   <div id="server">
        <div class="row-fluid"  >
            <div class="span12">
                <div class="portlet box green">
                    <div class="portlet-title">
                        <div class="caption"><i class="icon-globe"></i>信息列表</div>
                    </div>

                    <div class="portlet-body" >
                
                        <table class="table table-striped table-bordered table-hover table-full-width" id="sample_1">

                            <thead>

                                <tr>
                                    <th class="hidden-480">a</th>
                                    <th class="hidden-480">b</th>
                                    <th class="hidden-480">c</th>
                                    <th class="hidden-480">d</th>
                                </tr>

                            </thead>

                            <tbody>
                                    //循环赋值
                                    <foreach name=&#39;list&#39; item=&#39;info&#39;>
                                        <tr>
                                            <td>{$info.a}</td>
                                            <td>{$info.b}</td>     
                                            <td>{$info.c}</td>
                                            <td>{$info.d}</td>
                                         
                                        </tr>
                                    </foreach>
                                
                            </tbody>
                            
                        </table>
                        //分页信息
                        <div class="row-fluid"> {$page} </div>
                        
                    </div>
                </div>    
            </div>        
        </div>
</div>

이렇게 하면 페이지 번호를 클릭했을 때, 페이지가 매겨진 콘텐츠 위의 콘텐츠가 다시 로드되지 않습니다. 다시 한번 웹 페이지가 엉망이 됩니다

3.js 부분

이 단계는 ajax non-refresh 페이징을 구현하는 데 중점을 둡니다. jQuery의 ajax 상호 작용을 사용합니다. 데이터베이스를 사용하면 얻은 데이터가 템플릿에 기록되고 이전 데이터 세트가 페이징 목적을 달성합니다. server.js는 내부 또는 외부에서 작성할 수 있으며 자유롭게 선택할 수 있습니다

 3f1c4e4b6b16bbbd69b2ee476dc4f83a
    function server(pid){  
        var pid = pid;
        $.get("{:U('Index/page')}", "p="+pid, function(data){  
             $("#server").replaceWith("7db81b6f8cec3ce3f482d60b8ae1b72c"
             +data.content+
             "94b3e26ee717c64999d7867364b1b4a3"); 
        });
    }
2cacc6d41bbb37262a98f745aa00fbf0
이 메소드 이름 서버는 컨트롤러의 인스턴스화된 페이징 클래스에 전달되는 세 번째 매개변수입니다. 템플릿을 클릭하여 전환할 때마다 트리거됩니다. 이 js 메소드 서버(p)는 해당 페이지의 페이지 번호를 전달합니다.

$p=new \Think\AjaxPage($count,4,'server');
여기서 사용되는 것은 ajax와 백그라운드 간 통신을 위한 jQuery의 ajax 메소드의 .get 형식입니다. 반환된 데이터를 얻으려면

<div id=&#39;server&#39;>+数据</div>

를 사용하여 p를 서버 ID로 바꾸세요. 페이징 효과를 얻기 위한 템플릿입니다.

추천 학습: "

thinkphp 비디오 튜토리얼"

위 내용은 thinkphp에서 일부 콘텐츠의 ajax 비새로고침 페이징에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제