版权声明:引用请注明来源 https://blog.csdn.net/xfeng20/article/details/85759353
1、动态刷新机制
简介
通过js调用windows的定时函数 “setInterval()”,定时调用客户端的js代码,发起服务器请求,来达到数据的实时刷新
代码
test.c 代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
time_t current;
struct tm *timeinfo;
time(¤t);
timeinfo = localtime(¤t);
//这一句一定要加,否则异步访问会出现页面异常
printf("Content type: text/html\n\n");
printf("%s", asctime(timeinfo));
}
txmlhttpreq.js 代码
function createXHR()
{
var xhr;
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E)
{
xhr = false;
}
}
if (!xhr && typeof XMLHttpRequest != 'undefined')
{
xhr = new XMLHttpRequest();
}
return xhr;
}
/*
*异步访问提交处理
*/
function sender()
{
xhr = createXHR();
if(xhr)
{
xhr.onreadystatechange=callbackFunction;
//test.cgi后面跟个cur_time参数是为了防止Ajax页面缓存
xhr.open("GET", "cgi-bin/test.cgi?cur_time=" + new Date().getTime());
xhr.send(null);
}
else
{
//XMLHttpRequest对象创建失败
alert("浏览器不支持,请更换浏览器!");
}
}
/*
*异步回调函数处理
*/
function callbackFunction()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
var returnValue = xhr.responseText;
if(returnValue != null && returnValue.length > 0)
{
document.getElementById("current_time").innerHTML = returnValue;
}
else
{
alert("结果为空!");
}
}
else
{
alert("页面出现异常!");
}
}
}
test.html 代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>C+CGI+Ajax在S3C2440中的应用</title>
<script language="JavaScript" src="xmlhttpreq.js"></script>
<script>
setInterval(sender,500);
</script>
</head>
<body>
<h3>获取服务器当前时间</h3>
<p>服务器当前时间是:<div id="current_time"></div></p>
<input type="button" value="提交" onclick="sender()" />
</body>
</html>