[html]定时获取服务器时间和本地时间

2018-11-1 写技术

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
.time_div{width:100%; padding:10px; text-align:center; margin:5px auto; }
</style>
</head>

<div id="time_server" class="time_div"></div>
<div id="time_local" class="time_div"></div>

</html>

<script>
  var show_time_server = function(){
    var xhr = null;
    if(window.XMLHttpRequest){
      xhr = new window.XMLHttpRequest();
    }else{ // ie
      xhr = new ActiveObject("Microsoft")
    }
    // 通过get的方式请求当前文件
    xhr.open("get","/");
    xhr.send(null);
    // 监听请求状态变化
    xhr.onreadystatechange = function(){
      var time = null;
      var curDate = null;
      if(xhr.readyState===2){
        // 获取响应头里的时间戳
        time = xhr.getResponseHeader("Date");
        console.log(xhr.getAllResponseHeaders())
        curDate = new Date(time);
        document.getElementById("time_server").innerHTML = "服务器时间是:"+curDate.getFullYear()+"-"+(curDate.getMonth()+1)+"-"+curDate.getDate()+" "+curDate.getHours()+":"+curDate.getMinutes()+":"+curDate.getSeconds();
				setTimeout('show_time_server()', 1000);
      }
    }
  }
  
  var show_time_local = function(){
  	curDate = new Date();
		document.getElementById("time_local").innerHTML = "本地时间是:"+curDate.getFullYear()+"-"+(curDate.getMonth()+1)+"-"+curDate.getDate()+" "+curDate.getHours()+":"+curDate.getMinutes()+":"+curDate.getSeconds();
		setTimeout('show_time_local()', 1000);	
  }
  
  show_time_server();
  show_time_local();
</script>

标签: html

发表评论:

Powered by anycle 湘ICP备15001973号-1