前言:
現(xiàn)在前后端基本都是通過ajax實(shí)現(xiàn)前后端接口數(shù)據(jù)的交互,但是,ajax有個(gè)小小的劣勢,即:不支持瀏覽器“后退”和“前進(jìn)“鍵。
但是,現(xiàn)在我們可以通過H5的histroy屬性 解決ajax在交互請求的這個(gè)小bug。
事件描述:
H5增加了一個(gè)事件window.onpopstate,當(dāng)用戶點(diǎn)擊那兩個(gè)按鈕就會(huì)觸 發(fā)這個(gè)事件。但是光檢測到這個(gè)事件是不夠的,還得能夠傳些參數(shù),也就是說返回到之前那個(gè)頁面的時(shí)候得知道那個(gè)頁面的pageIndex。通過 history的pushState方法可以做到,pushState(pageIndex)將當(dāng)前頁的pageIndex存起來,再返回到這個(gè) 頁面時(shí)獲取到這個(gè)pageIndex。
window.history.pushState描述:
window.history.pushState(state, title, url);
state對象:是一個(gè)JavaScript對象,它關(guān)系到由pushState()方法創(chuàng)建出來的新的history實(shí)體。用以存儲關(guān)于你所要插入到歷史 記錄的條目的相關(guān)信息。State對象可以是任何Json字符串。因?yàn)閒irefox會(huì)使用用戶的硬盤來存取state對象,這個(gè)對象的最大存儲空間為640k。如果大于這個(gè)數(shù) 值,則pushState()方法會(huì)拋出一個(gè)異常。
title:firefox現(xiàn)在回忽略這個(gè)參數(shù),雖然它可能將來會(huì)被使用上。而現(xiàn)在最安全的使用方式是傳一個(gè)空字符串,以防止將來的修改。
url:用來傳遞新的history實(shí)體的URL,瀏覽器將不會(huì)在調(diào)用pushState()方法后加載這個(gè)URL。也許會(huì)過一會(huì)嘗試加載這個(gè)URL。比如在用戶重啟了瀏覽器后,新的url可以不是絕對路徑。如果是相對路徑,那么它會(huì)相對于現(xiàn)有的url。新的url必須和現(xiàn)有的url同域,否則pushState()將拋出異常。這個(gè)參數(shù)是選填的,如果為空,則會(huì)被置為document當(dāng)前的url。
直接貼代碼:
/**
* Created: Aaron.
* address: http://www.cnblogs.com/aaron-pan/
*/
//var pageIndex=window.history.state===null?0:window.history.state.page;
(function($,window,undefined){
var loadData={
pageIndex:window.history.state===null?1:window.history.state.page,
//pageIndex:0,
init:function(){
this.getData(this.pageIndex);
this.nextPage();
},
getData:function(pageIndex){
var that=this;
$.ajax({
type:'post',
url:'./data/getMovices'+pageIndex+'.json',
dataType:'json',
async:false,
success:function(data){
that.renderDom(data);
}
})
},
renderDom:function(movies){
var bookHtml=
"table>"+
"tr>"+
"th>電影/th>>"+
"th>導(dǎo)演/th>"+
"th>上映時(shí)間/th>"+
"/tr>";
for(var i=0;imovies.length;i++){
bookHtml +=
"tr>" +
" td>" + movies[i].moviesName + "/td>" +
" td>a>" + movies[i].moviesEditor + "/a>/td>" +
" td>" + movies[i].times + "/td>" +
"/tr>";
}
bookHtml+="/table>";
bookHtml +=
"button>上一頁/button>" +
"button class='nextPage'>下一頁/button>";
$('body').html(bookHtml);
},
nextPage:function(){
var that=this;
$(document).on("click",".nextPage",function(){
that.pageIndex++;
that.getData(that.pageIndex);
window.history.pushState({page:that.pageIndex},null,window.location.href);
//后退and刷新回到首頁 window.history.replaceState({page:that.pageIndex},null,window.location.href);
})
},
};
loadData.init();
window.addEventListener("popstate",function(event){
var page=0;
if(event.state!==null){
page=event.state.page;
console.log('page:'+page);
}
console.log('page:'+page);
loadData.getData(page);
loadData.pageIndex=page;
})
})(jQuery,window,undefined);
通過直接在html頁面調(diào)用js文件就可看到運(yùn)行結(jié)果。
運(yùn)行結(jié)果:

這樣就可以達(dá)到通過ajax進(jìn)行交互也能實(shí)現(xiàn)監(jiān)聽前進(jìn)/后臺/刷新的功能了。
附瀏覽器兼容性:

以上這篇通過history解決ajax不支持前進(jìn)/后退/刷新的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Ajax回退刷新頁面問題的解決辦法
- ajax后退解決方案