25-解决方案
17.6.2 解决方案
对这个问题的解决方案是将每个Ajax请求与一个独特的URL关联。这个URL可以加入书签,由浏览器的后退和前进按钮访问。方法之一是使用hash值。hash值通常用于链接到文档中的特定位置。http://en.wikipedia.org/wiki/Apple#History链接到维基百科上Apple词条的历史部分。在本秘诀中,hash值将引用Ajax请求加载的内容。
在这个例子中,样例项目是一个小的词汇表,表中有三个条目。当单击条目时,通过Ajax读取单词的定义并显示。当然,这样的内容可以一次性显示在单个页面上。但是,这里使用的方法可以用于更大、更多变的数据,例如,标签式界面中每个选项卡的内容:
<!DOCTYPE html>
<html><head>
<title>17.6 Dealing with Ajax and the Back Button</title>
<script src="../../jquery-1.3.2.min.js"></script>
<script src="jquery.history.js"></script>
</head>
<body>
<h1>17.6 Ajax and the Back Button</h1>
<a href="#apples" class='word'>apples</a>
<a href="#oranges" class='word'>oranges</a>
<a href="#bananas" class='word'>bananas</a>
<p id='definition'></p>
</body></html>
必要的JavaScript文件在文档头部包含。jquery.history.js文件包含jQuery历史插件(http://plugins.jquery.com/project/history)。词汇表中的三个条目各有一个锚元素。每个条目的定义将在 id 为 definition 的段落中显示:
(function($) {
function historyLoad(hash) {
if(hash) { $('#definition').load('server.php',{word: hash}); }
else { $('#definition').empty(); }
}
$(document).ready(function() {
$.history.init(historyLoad);
$('a.word').click(function() {
$.history.load($(this).html());
return false;
});
});
})(jQuery);
历史插件有两个值得考虑的函数: init() 和 load() 。 init() 函数在 ready 函数中调用,参数是处理Ajax请求的一个回调函数。 load() 绑定到单词链接,参数是每个锚标记的内容。回调方法 historyLoad() 负责请求传入hash值所指向的内容,还必须能够处理没有hash值的情况。