在最近的项目中,很多前端ajax表单提交后的跳转,因为使用了window.location.href 和 window.location.reload,产生了不同的效果,于是深入研究了一下window.location相关的函数。
window.location.href=“url”:改变客户端当前url
window.history.go(-1);window.history.back();后退,相当于浏览器“后退”按钮
window.location.replace(“url”):将地址替换成新url,该方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,你不能通过“前进”和“后 退”来访问已经被替换的URL,这个特点对于做一些过渡页面非常有用!
举个例子说明window.location.replace的作用,有三个页面:1.html, 2.html, 3.html
首先页面3.html的代码一直固定。
<script>
window.history.back();
</script>
==window.location.replace==
首先访问1.html,然后在浏览器栏改网址访问2.html。
2.html代码如下:
<script> window.location.replace('3.html'); </script>
这样用浏览器的前进、后退,或者使用window.history.go(-1);window.history.back();只能在1.html和3.html中切换,无法访问到跳转页面2.html
该结论在ie8, firefox3, chrome9, opera10, safari4验证通过
==window.location.href==
首先访问1.html,然后在浏览器栏改网址访问2.html。
2.html代码如下:
<script> window.location.href = '3.html'; </script>
当在3.html用浏览器的前进、后退,或者使用window.history.go(-1);window.history.back();
不同浏览器效果如下:
ie8 跳到2.html
safari4 跳到2.html
opera10 跳到1.html
chrome9 跳到1.html
firefox3 跳到1.html
window.location.reload([bool]):强制刷新页面,从服务器重新请求!如果有post请求也会强制重新发送请求。
reload(true)是从服务端重新拿一下所有的页面组件,像image,css,js都得从拿,所以速度比较慢
reload(false)则是从本地缓存中拿页面组件,但是好像html自身不会缓存,所以一般用reload(false)就可以,具体是不是就不大清楚了 如果超出假设,可以考虑href,assign,replace等方法。