HTML5 : History API

9,076 阅读2分钟

History API

可以在不刷新页面的前提下动态改变浏览器地址栏中的URL地址,动态修改页面上所显示资源。

window.history 的方法和属性

方法:back() forward() go()
属性:length
//返回
window.history.back()
window.history.go(-1)
//向前跳转
window.history.foward()
window.history.go(1)
//历史记录中页面总数
history.length

HTML5 新方法:添加和替换历史记录的条目

pushState
history.pushState(state, title, url); 添加一条历史记录,不刷新页面
参数
state : 一个于指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数中。如果不需要这个对象,此处可以填null。
title : 新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null。
url : 新的网址,必须与前页面处在同一个域。浏览器的地址栏将显示这个网址。
创建2个文档,demo.html和index.html,更改它们的title为对应的名字,并在body里输入文档名字作为内容标记文档。
//index.html
history.pushState(null, null,'./demo.html')
浏览器没有刷新加载demo.html,只是更改浏览器地址栏地址
//index.html
history.pushState(null, null,'./demo.html')
history.pushState(null, null,'./inexistence.html')

不会检查inexistence.html是否存在
应用--添加hash值,页面只局部加载
//index.html
history.pushState(null, null,'#one')
replaceState
history.replaceState(state, title, url); 替换当前的历史记录,不刷新页面
//demo.html
history.replaceState(null, null,'?one')
当前的历史记录http://localhost/class/demo.html被替换为http://localhost/class/demo.html?one

事件

1.popstate 事件:历史记录发生改变时触发,调用history.pushState()或者history.replaceState()不会触发popstate事件
2.hashchange 事件:当页面的hash值改变的时候触发,常用于构建单页面应用。

应用

点击botton,content区出现对应的内容,通过浏览器返回按钮可以返回上一个内容页面。
HTML
<div class="wrapper">
    <div class="header">
        <!-- 设置data值标记每个地址 -->
        <button data="first">first</button>
        <button data="second">second</button>
        <button data="third">third</button>
    </div>
    <div class="content">
        <div class="item">first</div>
    </div>
</div>
JS
var item = document.getElementsByClassName('item')[0];
var header = document.getElementsByClassName('header')[0];
var page = '';
function init(){
    //替换页面的历史记录,并把{newPage : 'first'}传入这条历史记录下,方便后期popstate调用
    history.replaceState({newPage : 'first'}, null, '?first');
    ajax('GET','./getContent.php','page=first', doData, true)
}
init();
function doData(data){
    //将ajax获取的数据插入到item元素节点里面
    item.innerHTML = data;
}
header.addEventListener('click', function(e){
    
    page = e.target.getAttribute('data');
    history.pushState({newPage : page}, null, '?'+page);
    ajax('GET', './getContent.php','page='+page, doData, true);
})
//当页面前进与后退的时候,popstate监听历史记录变化,触发对应页面的ajax请求。
window.addEventListener('popstate', function(e){
    // console.log(e)
    var newPage = e.state.newPage;
    ajax('GET', './getContent.php','page='+newPage, doData, true);
})
php
<?php
header('content-type:text/html;charset="utf-8"');
error_reporting(0);

$page = $_GET['page'];
if($page == 'first'){
    $data = 'first third';
}else if($page == 'second'){
    $data = 'second third';
}else if($page == 'third'){
    $data = 'third third';
}

echo"{$data}";