pjax使用教程-绝对实用

分类:Javascript |

pajax库文件请到github下载,地址见文章底部。

需要先引入jquery,再引入pjax

步骤:

一、首先你的项目需要有两个页面,page1.html, page2.html,现在的需求是在page1.html点击一个超级链接跳转到page2.html的时候能直接更新网页内容而不需要重新刷新整个网页。

二、在page1.html中创建一个class为main-wrap的div,在里面随意添加一些内容。然后在div的后面添加一个跳转到page2.html的超级链接:<a  data-pjax href="./page2.html"></a> ,并在文件中引入jquery和pjax

三、我想你现在应该注意到了这个标签里面有个属性data-pjax,加这个标签是告诉pjax只有添加了data-pjax属性的a标签的跳转才交到pjax处理,其他的还是刷新的方式加载。

四、将page1.html的内容复制到page2.html,之后修改page2中main-wrap的内容跟原来不一样就可以了,。

当然我这只是以一个demo的方式来讲解,读者可以把pjax用在自己的项目中就可以了。

好了,现在点击page1.html中的那个a标签,现在可以看到main-wrap中的内容被页面page2中的main-wrap替换掉了。

下面是我pjax代码的部分,注释可能对你有所帮助的哦【血的教训:请不要有拼写错误!请不要有拼写错误!请不要有拼写错误!重说三】:

/* pjax */if ($.support.pjax) {
    $(document).pjax('a[data-pjax]', '.main-wrap', {        // 本页面的ID        fragment: '.main-wrap',                          //来源也的ID        timeout: 200000000,
        show: 'fade',
        cache: true,  //是否使用缓存        push: true,
        replace: true,
        //scrollTo: 250,    });
    $(document).on('pjax:send', function () { //pjax链接点击后显示加载动画        $("#progress").removeClass("done");//完成,隐藏进度条        $({property: 0}).animate({property: 100}, {
            duration: 500,
            step: function () {
                var percentage = Math.round(this.property);

                $('#progress').css('width', percentage + "%");

                if (percentage == 100) {
                    $("#progress").addClass("done");//完成,隐藏进度条                }
            }
        });
    });//加载完成后替换title    $(document).on('pjax:success', function (data, status, xhr, options) {

        $('title').text(data.relatedTarget.innerText + ' - 啊啦资讯');

    });
    $(document).on('pjax:complete', function () {
        $("#progress").addClass("done");//完成,隐藏进度条    });

    $(document).on('pjax:error', function () {
        alert("加载失败!");
    });

}

加载条html:

<div id="progress">    <span></span></div>

加载条CSS:

/* PROGRESS BAR */#progress {
    position:fixed;
    height: 2px;
    top: 0;
    background:#32BACA;
    transition:opacity 500ms linear
}#progress.done {
    opacity:0}#progress span {
    position:absolute;
    height:2px;
    -webkit-box-shadow:#32BACA 1px 0 6px 1px;
    -webkit-border-radius:100%;
    opacity:1;
    width:150px;
    right:-10px;
    -webkit-animation:pulse 2s ease-out 0s infinite;
}

@-webkit-keyframes pulse {
    30% {
        opacity:.6    }
    60% {
        opacity:0;
    }
    100% {
        opacity:.6    }
}


官方地址:https://github.com/defunkt/jquery-pjax

转自: https://my.oschina.net/Jakesoft/blog/517158



 如果使用了多说的评论, pjax后需要回调函数 加载多说 

 function pajx_loadDuodsuo(){ var dus=$(".ds-thread"); if($(dus).length==1){
     var el = document.createElement('div');
     el.setAttribute('data-thread-key',$(dus).attr("data-thread-key"));//必选参数
     el.setAttribute('data-url',$(dus).attr("data-url"));
     DUOSHUO.EmbedThread(el);
     $(dus).html(el);
 }