如果将clock.innerHTML=_time;移到注释 //①下面的话,那么_time将没有值,求教
<html><head>
<style type="text/css">
.clock
{
padding :10px;
color:white;
text-align:center;
height:12%;
width:25%;
margin-left:35%;
margin-right:35%;
border:solid 10px black;
background:gray;
}
</style>
<meta http-equiv="content-type" content="text/html; charset=GBK" />
<script type="text/javascript" >
function disp()
{
var xmlhttp;
var _time="sss";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
_time=xmlhttp.responseText;
clock.innerHTML=_time;
}
}
xmlhttp.open("POST","MyJsp.jsp?t="+Math.random(),true);
xmlhttp.send();
//①
}
</script>
</head>
<body >
<div id="clock" class="clock" > </div>
<script type="text/javascript">
setInterval("disp()",1000);
</script>
</body>
</html>
_time在请求后xmlhttp.responseText返回的是空值吗?
断点检查下
由于ajax是异步,所以在state状态还没有完全到4时,clock.InnerHTML=_time已经执行完毕,而等状态到4时_time被赋值,这个方法已经执行结束了,1S后又开始重新执行disp()方法。
要将此值显示,可以尝试用setTimeout()延迟1S执行clock.InnerHTML=_time。(该方法也显示不出,如果延迟1S,那么在这1S期间不会去执行onstateChage(),而是1S后执行clock.InnerHTML=_time,再去执行Onstatechange();唯有将AJAX设置为同步,等其将数据完全解析完毕才行)