js向服务器发送请求,获取服务器时间

1.打开开发者工具中的console


2.复制下面代码

ajax()
  function ajax(option){
    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,
          curDate = null;
      if(xhr.readyState===2){
        // 获取响应头里的时间戳
        time = xhr.getResponseHeader("Date");
        console.log(xhr.getAllResponseHeaders())
        curDate = new Date(time);
        document.getElementById("time").innerHTML = "服务器时间是:"+curDate.getFullYear()+"-"+(curDate.getMonth()+1)+"-"+curDate.getDate()+" "+curDate.getHours()+":"+curDate.getMinutes()+":"+curDate.getSeconds();
      }
    }
  }

3.完成代码后回车,等待服务器返回时间



猜你喜欢

转载自blog.csdn.net/jiangzhanweiabc/article/details/78499948