一个简单的例子看明白如何利用window.location.hash实现ajax操作

我们知道JavaScript中很早就提供了window.history对象,利用history对象的forward()、go()、back()方法能够方便实现不同页面之间的前进、后退等这种导航功能。但是AJAX操作,是不能用浏览器的前进和后退按钮进行导航的,因为浏览器并不会将AJAX操作加入到历史记录中。但是借助location.hash,我们能够自己实现AJAX操作的前进和后退。关于window.location.hash的详细介绍和使用方式,可以参考下面这2篇文章。

location.hash详解和 6 Things You Should Know About Fragment URLs。

我们需要知道以下2点:

1.如果location.hash发生了变化,那么浏览器地址栏url会发生变化,,而且浏览器会产生1个历史记录。

2.如果location.hash发生了变化,会产生一个hashchange事件,我们可以处理这个事件。

<!DOCTYPE html> <html><head><meta charset="utf-8"><script type="text/javascript" src="jquery-1.11.1.min.js"></script><script type="text/javascript">var currentPageIndex = 0;window.onload = function(){currentPageIndex = 0;showPageAtIndex(currentPageIndex);recordHash(currentPageIndex);}// onhashchange可以监控hash变化window.onhashchange=function(){var hash = window.location.hash;var id = parseInt(hash.substr(1));showPageAtIndex(id);};function toNextPageWhenClick(){currentPageIndex++;if(isValidPageIndex(currentPageIndex)){showPageAtIndex(currentPageIndex);recordHash(currentPageIndex);}else{return;}}function showPageAtIndex(id){$("div[id!="+id+"]").hide();$("#"+id).show();if(isHomePage(id)){$("input").attr("value","current is home page,next page=1");}else if(isLastPage(id)){$("input").attr("value","current page="+id+", it is the end.");}else{$("input").attr("value","current page="+id+",next page="+(id+1));}}function isValidPageIndex(id){return id <= 5;}function isLastPage(id){return id == 5;}function isHomePage(id){return id == 0;}// hash改变,浏览器会自动生成一个历史记录function recordHash(id){window.location.hash=id;}</script><style>.navigate{height:100px;width:300px;background-color:#0000ff;display:none;}.home{height:100px;width:300px;background-color:#00ff00;display:none;}.last{height:100px;width:300px;background-color:#ff0000;display:none;}</style></head> <body><input type="button" value="" onclick="toNextPageWhenClick();"><div class="home" id="0">HOME PAGE</div><div class="navigate" id="1">ajax1</div><div class="navigate" id="2">ajax2</div><div class="navigate" id="3">ajax3</div><div class="navigate" id="4">ajax4</div><div class="last" id="5">last page</div></body></html>

在chrome下运行这个html文件,默认显示home page,点击按钮的时候回调到下一个页面(直到最后一个页面为止)。我们可以点击浏览器的前进、后退按钮,实现模拟ajax前进、后退的功能。

更重要的是心理上的完全自由和放松,

一个简单的例子看明白如何利用window.location.hash实现ajax操作

相关文章:

你感兴趣的文章:

标签云: