嵌入式Linux之我行——C+CGI+Ajax在S3C2440中的应用

http://blog.chinaunix.net/uid-22174347-id-1786907.html

1,建立文件test.html

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <title>liuxizhen</title>
  <script language="JavaScript" src="xmlhttpreq.js"></script>
 </head>
 <body>
  <h3>获取服务器当前时间</h3>
  <p>服务器当前时间是:<div id="current_time"></div></p>
  <input type="button" value="提交" οnclick="sender()" />
 </body>
</html>


2,建立js文件xmlhttpreq.js

 特别注意其中的在回调函数里有个setTimeout,还设置客户端的更新周期。

 

/*
 *创建异步访问对象
 */
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", "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;
                
                setTimeout(sender, 1000);
            }
            else
            {
                alert("结果为空!");
            }
        } 
        else 
        {
            alert("页面出现异常!");
        }
    }
}
/*
setTimeout(sender, 1000);
*/



3,建立linux下的cgi文件

#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));
}

生成test.cgi的可执行文件。

将test.cgi和html,js文件放在服务器的www目录下。登录服务器查看,时间就是变化的,可以自动更新的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值