美文网首页
Jquery局部刷新插件Pjax

Jquery局部刷新插件Pjax

作者: Separes | 来源:发表于2017-02-13 11:09 被阅读720次

    Pjax是对Ajax + pushState的封装,可以实现网页的ajax加载,改变网页URL却不会刷新网页整体本身,避免重新加载网页中大部分的控件和插件。
    pushState的功能具体来说就是修改url而页面无跳转,并且该url会被存放在历史记录中。

        window.history.pushState(state, title, url);
    

    GitHub传送门:
    https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js

    pjax执行流程:

    • 1.触发事件后执行相关语句或者函数,包装成为ajax向服务器请求数据;

        options = $.extend(true, {}, $.ajaxSettings, pjax.defaults, options)
        pjax.options = optionsvar xhr = pjax.xhr = $.ajax(options)
      
    • 2.给请求附加X-PJAX标识,服务器只会返回Container中的内容:

        xhr.setRequestHeader('X-PJAX', 'true')
        xhr.setRequestHeader('X-PJAX-Container', context.selector)
      
    • 3.更新Container的内容;

        function pjaxReload(container, options)
        {  var defaults = 
        {    url: window.location.href,
            push: false,
            replace: true,
            scrollTo: false
        }
        return pjax($.extend(defaults, optionsFor(container, options)))}
      
    • 4.pushState 方法把当前的页面的地址、标题等信息放入浏览器历史记录中

        if (xhr.readyState > 0)
        { if (options.push && !options.replace) 
        {      // Cache current container element before replacing it
              cachePush(pjax.state.id, cloneContents(context))
              window.history.pushState(null, "", options.requestUrl)
        }
        fire('pjax:start', [xhr, options])
        fire('pjax:send', [xhr, options])
        }
        return pjax.xhr
        }
      
    • 5.利用replaceState更新浏览器地址;
      function locationReplace(url)
      { window.history.replaceState(null, "", pjax.state.url)
      window.location.replace(url)
      }

    相关文章

      网友评论

          本文标题:Jquery局部刷新插件Pjax

          本文链接:https://www.haomeiwen.com/subject/dsbzittx.html