js定时刷新数据

首先准备一个测试页面:

1 <!--html代码-->
2 <h1 id="test">页面刷新</h1>
3 <button onclick="fresh()">刷新</button
复制代码
1 //script
2 var h1 = document.getElementById('test');
3 function test(){
4      h1.style.color = "red";
5      h1.innerText = "我变化了";
6 }
7 setInterval(test, 1000);
复制代码

准备工作完成,开始页面刷新方法:

1.可以正常使用的五种方法:

1 //第一种方法
2 function fresh(){
3       window.location.reload();//强迫浏览器刷新当前页面,默认参数为false,表示从客户端缓存里取当前页。如果指定为true,则以GET方式从服务端取最新的页面,相当于客户端点击F5。
4 }
1 //第二种方法
2 function fresh(){
3       history.go(0);
4 }
1 //第三种方法
2 function fresh(){
3       location = location;
4 }
1 //第四种方法
2 function fresh(){
3       location.assign(location);//assign()方法加载一个新的文档。
4 }
1 //第五种方法
2 function fresh(){
3      location.replace(location);//通过指定URL替换当前缓存在历史里(客户端)的项目,所以使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL。
4 }

2.只在ie可以执行的两种方法:

1 //第六种方法
2 function fresh(){
3       document.execCommand('Refresh');//是只有IE提供的方法,叫浏览器方法。
4 }
1 //第七种方法
2 function fresh(){
3       window.navigate(location);//只在ie可以执行,不适用于火狐等其他浏览器。
4 }

3.网上很容易找到,但是个人认为是错误的一种方法:

1 //错误方法
2 function fresh(){
3       document.URL=location.href;//错误用法,document.URL只能读不能写
4 }

但是也可以有替代的方法:

复制代码
1 //第八种方法
2 //window.location.href和document.location.href可以被赋值,然后跳转到其它页面
3 //一个窗口下只有一个window.location.href,但是可能有多个document.URL、document.location.href
4 function fresh(){
5       document.location.href = location.href;
6       //可以使用,document表示的是一个文档对象   
7 }
复制代码
1 //第九种方法(与第八种方法是一类)
2 function fresh(){
3      window.location.href = location.href;//可以使用,window表示的是一个窗口对象
4 }

如有错误,请您指正!

接下来进入正题-定时不断刷新页面的方法:

1.看到定时,很容易想到js的定时器:

复制代码
1 //第一种方法
2 //由于我们已经有了一个定时器,所以只要在定时器test中加入一句刷新页面的代码即可
3 function test(){
4      h1.style.color = "red";
5      h1.innerText = "我变化了";
6      history.go(0);//可以换成上一篇博客的任何一种方法。
7 }
8 setInterval(test, 1000);
复制代码

2.通过meta来设置:

1 <!--第二种方法-->
2 <!--定时自动刷新,content表示刷新间隔,单位为秒s,下面代码表示页面每隔三秒刷新一次-->
3 <meta http-equiv="refresh" content="3">
1 <!--第三种方法-->
2 <!--这种方法实现页面刷新有点投机取巧,这个标签作用是定时跳转,content第一个参数表示间隔时间,单位为秒,第二个参数表示目标网址,但是如果把第二个参数设为#,就会实现页面刷新。-->
3 <meta http-equiv="refresh" content="3;url=#">

如有错误,请您指正!

posted @ 2019-12-03 22:01  AnthonyWang  阅读(6700)  评论(0编辑  收藏  举报