Ajax七宗罪第五宗里面,作者讽刺Ajax需要一个“没有back和history的浏览器”。很讽刺吗?只是作者这么想罢了。至少要让Ajax应用支持Forward和Back,并不需要什么了不起的技术,我们也不需要这样的浏览器来改变用户习惯,事实上我们完全能做到让Forward和Back更酷。
这是一个示范页面:
index.htm
<HTML>
<BODY>
<textarea cols=80 rows=30 id="textarea1" onkeypress="checkSave()">请在此处输入</textarea>
<iframe name=historyFrame width=0 height=0 src="hiddenpage.htm?0#0"></iframe>
<SCRIPT LANGUAGE="JavaScript">
<!--
historyFrame.history.go(-999)
var t = document.getElementById("textarea1");
var maxHistory=100;
var historyList=[];
var historyOffset=0;
var timer;
function checkSave(){
if(timer)clearTimeout(timer);
timer=setTimeout(saveHistory,500);
}
function saveHistory(){
if(t.value==t.oldValue) return;
historyList[historyOffset]=t.oldValue;
historyOffset++;
historyList.length=historyOffset
t.oldValue=t.value;
var url = historyFrame.location.protocol+"//"+historyFrame.location.pathname+"?";
historyFrame.location=url+(historyOffset%2)+"#"+historyOffset;
t.focus();
}
function gotoHistory(n){
if(n<historyOffset){
historyList[historyOffset]=t.value;
}else if(n>historyOffset){
}else return;
historyOffset=n;
t.value=historyList[historyOffset];
t.focus();
}
window.onload=function(){
t.oldValue=t.value;
}
//-->
</SCRIPT>
</BODY>
</HTML>
需要一个简单的页面放在同一目录下面:
hiddenpage.htm
<SCRIPT>window.onload=function(){parent.gotoHistory(location.hash.substr(1))}</SCRIPT>
好了,打开index页面,在文本区域里面做一些输入,然后试试IE的前进和后退按钮能提供多酷的功能。
这个方法由emu的好朋友twinsen首先提出来,以后我们就叫它twinsen方法吧。