ajaxtest.html文件
Ajax + CGI Test获取服务器当前温度
服务器当前温度 是:
ajaxtest.js文件
var xmlhttp;
/*
*创建异步访问对象
*/
function createXHR()
{
var xhr;
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e2)
{
xhr = false;
}
}
if(!xhr && typeof XMLHttpRequest !='undefined')
{
xhr = new XMLHttpRequest();
}
return xhr;
}
/*
*异步访问提交处理
*/
function sender()
{
xmlhttp = createXHR();
if(xmlhttp)
{
xmlhttp.onreadystatechange=callbackFunction;
/*test.cgi后面跟个cur_time参数是为了防止Ajax页面缓存*/
xmlhttp.open("GET","ajaxtest.cgi?cur_time="+new Date().getTime(),true);
xmlhttp.send(null);
}
else
{
/*XMLHttpRequest对象创建失败*/
alert("浏览器不支持,请更换浏览器!");
}
}
/*
*异步回调函数处理
*/
function callbackFunction()
{
if(xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
var returnValue = xmlhttp.responseText;
if(returnValue != null && returnValue.length > 0)
{
document.getElementById("current_time").innerHTML = returnValue;
}
else
{
alert("结果为空!");
}
}
else
{
alert("页面出现异常!");
}
}
}
服务器上应该有ajaxtest.cgi程序更新温度并返回温度
以上html稍微修改下 放到定时器定时调用应该就可以
在sender()中,加上setTimeout,每隔两秒调用它本身就可以实现了。
感谢网名:armips的网友的贡献
另附参考文章: