XMLHttpRequest使用
<span id="clock"></span>
<script type="text/javascript">
//对没有XMLHttpRequest对象的浏览器,需要构造一个
if (!window.XMLHttpRequest)
window.XMLHttpRequest = function () {
return new ActiveXObject("Microsoft.XMLHTTP");
}
//function UpdateClock()//动态刷新时钟函数
//{
// //建立一个XMLHttpRequest对象去请求ServerTime.ascx控件
// var aRequest = new XMLHttpRequest();
// aRequest.open("POST", "/Home/GetServerTime", false);//同步调用
// aRequest.send("");
// document.getElementById("clock").innerHTML = aRequest.responseText;
//}
//setInterval(UpdateClock, 1000);//每隔一秒调用一次UpdateClock函数
function AsynRequest()
{
var aRequest = new XMLHttpRequest();
aRequest.open("POST", "/Home/GetServerTime", true);
//在请求头部说明本次请求的是Json格式数据
aRequest.setRequestHeader("Content-Type", "application/json;charset=utf-8");
aRequest.onreadystatechange = function () {
if (aRequest.readyState == 4)
{
var result = eval("("+aRequest.responseText+")");
UpdateClock(result);
}
};
aRequest.send("");
}
function UpdateClock(aTime)
{
document.getElementById("clock").innerHTML = aTime;
}
setInterval(AsynRequest, 1000);
</script>