pjax+thinkphp5实现url跳转网页局部刷新效果

经验分享  2018-08-07 14:34   8242 pjax thinkphp5

使用ajax来异步加载数据列表不利于SEO优化,页面局部刷新URL地址不变,虽然说用户体验比全页面刷新好一点,可是爬虫爬取会认为是一个页面,影响收录。这里将介绍使用Pjax加载页面,实现URL跳转网页局部刷新效果。

后台框架服务使用thinkphp5,前台渲染加载使用Pjax。


thinkphp5代码

文件 controller/home/index.php

    /**
     * pjax 渲染
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    protected function render_pjax($data)
    {
        $this->assign('data', $data);
        if ($this->request->isPjax())
        {
            $this->view->engine->layout(false);
            exit($this->fetch('pjaxlist')); 
        } else {
            return $this->fetch(); 
        }
    }
    
    public function index ()
    {
        $data = []; // 查询数据
        return $this->render_pjax($data);
    }

javascript:

pjax有多种请求加载渲染方式,点击链接加载比较简单,这里实现这种比较通用的,可以放到js方法中。

        $.pjax({
            container:'#pjax-container',
            url:pjax_url,  // pjax 请求地址
            timeout:6000,  // 超时时间  超时将全页面跳转刷新
            push:true,
            scrollTo:100px,  // 向上滚动
        });

HTML:

文件 view/home/pjaxlist.html

<ul>
    <! -- 循环 -->
    <li>
       <!-- 赋值 -- >
    </li>
    <! -- 循环 -->
</ul>

文件 view/home/index.html

<html>
<head>
    <script src="jquery.js"></script>
    <script src="jquery.pjax.js"></script>
</head>
<body>
    <div id="pjax_container">
     <!-- 加载内容 -->
    </div>
    <a href="javascript:load()">加载内容</a>
    <script>
       function load()
       {
          var pjax_url = '/home/index';
          $.pjax({
            container:'#pjax-container',
            url:pjax_url,  // pjax 请求地址
            timeout:6000,  // 超时时间  超时将全页面跳转刷新
            push:true,
            scrollTo:100px,  // 向上滚动
        });
       }
    </script>
</body>
</html>
注:本文转载自原创,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除。

沙豆网 站长

追求卓越,奋斗不息!

167
文章
8811
点赞

更多文章