網頁資料實時更新的三種簡單方法
一、頁面自動重新整理
<meta http-equiv="refresh" content="20">
其中20指每隔20秒重新整理一次頁面.
二、頁面自動跳轉:
<meta http-equiv="refresh" content="20;url=http://www.hackhome.com">
其中20指隔20秒後跳轉到http://www.hackhome.com頁面
三、js控制
<script language="JavaScript">
function myrefresh(){
window.location.reload();
}
setTimeout('myrefresh()',1000); //指定1秒重新整理一次
</script>
四、Ajax
var isLoaded = false;
function reqs(opts) {
$.ajax({
type: 'get',
url: 'demo.php',
dataType: 'json',
beforeSend: function() {
if(opts.init === 1) {
$('.zh-loading').show();
}
isLoaded = false;
},
success: function(res) {
console.log(res);
},
complete: function() {
if(opts.init === 1) {
$('.zh-loading').hide();
}
isLoaded = true;
},
error: function() {
console.log('請求失敗~');
}
});
}
reqs({"init": 1});
setInterval(function() {
isLoaded && req({"init": 0});
}, 3000);
註釋:
1.isLoaded && req({"init": 0}); 表示前面一個條件正確,則執行&&後面的方法。
2.將init賦值為0,是讓loading只出現在頁面第一次載入的時候。後面不出現。