ajax获取服务器当前时间

2014-11-24 01:42:53 · 作者: · 浏览: 1
通过ajax获取response header 上的date值,注意时区,在chrome 开发工具header中看到的均为格林威治时间,比北京时间小8个小时,获取的时区与服务器端设置有关系。 推荐下面方法:
//从response header中获取服务器当前时间,不存在有缓存时的问题
function getServerTime(){
     var xmlHttp = false;
     try {
       xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
       try {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (e2) {
          xmlHttp = false;
       }
     }
    
     if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
       xmlHttp = new XMLHttpRequest();
     }
    
     xmlHttp.open("GET", window.location.href.toString(), false);
     xmlHttp.setRequestHeader("Range", "bytes=-1");
     xmlHttp.send(null);
    
     var severtime=new Date(xmlHttp.getResponseHeader("Date"));
     return severtime
}

另外,通过jquery的ajax方法获取,存在缓存不更新时间的问题。
htmlobj=$.ajax({url:"a.txt",async:false});
$("#myDiv").html(htmlobj.responseText);
responseText:返回的内容
async:false指有返回值后才执行后面的代码(同步线程)
htmlobj.getResponseHeader("Date")
取得response header中时间(格林威治时间,比北京时间慢8小时),
有缓存时,IE下取值为null,chrome时间不会更新
firefox频繁请求,时间上会有延迟,在某一时间段内时间不会更新(距前一次刷新约一分钟的样子)。