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

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

2018-11-1 萧 写技术

.time_div{width:100%; padding:10px; text-align:center; margin:5px auto; }

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();

发表评论:

昵称

邮件地址 (选填)