在客户端使用html网页时,有时需要传递参数给客户端,使用cgi就比较轻松的实现这个功能,例程如下,
用户在客户端打开网页login.html登录,输入用户名和密码,提交,调用服务端的login.cgi程序,同时将参数传递给login.cgi,
下面这种方面可以不打开新页面,而完成后台运行
login.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312"/>
<title>C+CGI+AJAX测试</title>
<script>
function createXHR()
{
var xhr;
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xhr = new ActiveObject("Microsoft.XMLHTTP");
}
catch(E)
{
xhr = false;
}
}
if(!xhr && typeof XMLHttpRequest != 'undefined')
{
xhr = new XMLHttpRequest();
}
return xhr;
}
function sender(val)
{
xhr = createXHR();
if(xhr)
{
xhr.onreadystatechange = callbackFunction;
xhr.open("GET","./cgi-bin/login.cgi?"+val); //调用login.cgi程序,val为需要传递的参数
xhr.send(null);
}
else
{
alert("浏览器不支持,请更换浏览器!");
}
}
function callbackFunction()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
var returnValue = xhr.responseText;//returnValue为login.cgi返回的结果
if(returnValue=="login success")
window.location.replace('main.html');
else
document.getElementById("current_time").innerHTML = "用户名或密码错误";
}
else
{
alert("页面出现异常!");
}
}
}
function ok()
{
val = "username="+document.message.username.value+"&password="+document.message.password.value; //val为需要传递的用户名和密码
sender(val);
}
</script>
</head>
<body>
<center>
<p><div id="current_time">
</div>
<form name="message">
用户名: <input type="text" INPUT NAME="username" SIZE="30" maxlength="20"><p>
<P>密码: <input type="password" INPUT NAME="password" SIZE="30" maxlength="20"><p></p>
<input type="button" value="提交" onclick="ok()"/>
<input type=reset value="重置">
</form>
</center>
</body>
</html>
login.c
#include <stdio.h>
#include <stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include <time.h>
struct logindata{
char username[20];
char password[20];
};
struct userdata{
char username[20];
char password[20];
};
int main(void)
{
FILE *userfp = NULL;
char *date;
struct logindata loginsave;
struct userdata userread;
printf("Content type: text/html;charset=gb2312\n\n");
date = getenv("QUERY_STRING");
if(date == NULL)
printf("Data transmission error");
else{
sscanf(date,"username=%[^&]&password=%s",loginsave.username,loginsave.password);
if((userfp = fopen("/config/user.conf","rw")) == NULL) //wirte only
{
printf("fail to open /config/user.conf file!\n");
return -1;
}
if((fread(&userread,sizeof(userread),1,userfp)) != 1)
{
printf("read /config/user.conf faild");
fclose(userfp);
return -1;
}
if((strcmp(loginsave.username,userread.username)==0)&&(strcmp(loginsave.password,userread.password)==0))
{
printf("login success");
}
else{
printf("username or password wrong\n");
}
}
return 0;
}