为了账号安全,请及时绑定邮箱和手机立即绑定

ajax获取的服务器时间怎么赋值给js的全局变量?

ajax获取的服务器时间怎么赋值给js的全局变量?

qq_控心_0 2017-02-14 12:20:10
赋值给ends,显示不出来,哪里错了?代码如下<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p id="time"></p>  </body> <script>  var ends; ajax()  function ajax(option){  var xhr = null; if(window.XMLHttpRequest){ xhr = new window.XMLHttpRequest(); } else{  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); ends=curDate.getTime(); } }  } document.getElementById('time').innerHTML=ends;  </script></html>
查看完整描述

1 回答

已采纳
?
Caballarii

TA贡献1123条经验 获得超629个赞

如果你console.log(xhr.getAllResponseHeaders())能打印出东西,那么你就应该把document.getElementById('time').innerHTML=ends;直接放到ends=curDate.getTime();这句之后

查看完整回答
反对 回复 2017-02-14
  • qq_控心_0
    qq_控心_0
    我知道放在之后可以,但是这个document.getElementById('time').innerHTML=ends;只是一个例子,我需要获取curDate.getTime()这个值用到函数里
  • qq_控心_0
    qq_控心_0
    谢谢你的回答
  • Caballarii
    Caballarii
    那你的函数只能写在document.getElementById('time').innerHTML=ends;这句话的位置,因为只有在回调函数里才能取到curDate.getTime()的值,顺序写在ajax()函数之后是没有用的,这也是js最重要的异步回调原理
点击展开后面5
  • 1 回答
  • 0 关注
  • 1683 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信