环境:centos 6.5
web容器:apache2.4,[
准备:
cd /usr/local/httpd-2.4.20/modules/generators \enter
cp mod_cgi.c /usr/local/apache/bin \enter
./apxs -i -a -c mod_cgi.c \enter
cd usr/local/apache/conf/
vim httpd.conf (找到loadModule xxxx xxxx 的地方,在后面添加 loadModule cdg_module modules/mod_cgi.so)
cd ../bin \enter
./httpd -k restart
在/usr/local/apache/htdocs/添加 index.html
It works!hahahahhahaha~
functiontestcgi(){
$.ajax({
type:'POST',
url:'../cgi-bin/cgitest.cgi',
data:"hello world",
dataType:"text",
ContentType:"application/text; charset=utf-8",
success:function(returnedData,status) {if(status=="success"){
alert(returnedData);
}
},
error:function(msg) {
alert("访问失败:"+msg);
}
});
}
在/usr/local/apache/cgi-bin添加 cgitest.c
#include #include#include#include
#define MAXLEN 1024
char* getcgidata(FILE* fp, char*requestmethod);int main(void)
{char * cgistr =NULL;char * req_method =NULL;
printf("Content-type: application/text;charset=utf-8\n\n");
req_method= getenv("REQUEST_METHOD");
cgistr=getcgidata(stdin, req_method);
fprintf(stdout,"you post param is %s",cgistr);
}char* getcgidata(FILE* fp, char*requestmethod)
{char*input;intlen;int size =MAXLEN;int i = 0;if (!strcmp(requestmethod, "GET"))
{
input= getenv("QUERY_STRING");returninput;
}else if (!strcmp(requestmethod, "POST"))
{
len= atoi(getenv("CONTENT_LENGTH"));
input= (char*)malloc(sizeof(char)*(size + 1));if (len == 0)
{
input[0] = '\0';returninput;
}while(1)
{
input[i]= (char)fgetc(fp);if (i ==size)
{
input[i+1] = '\0';returninput;
}--len;if (feof(fp) || (!(len)))
{
i++;
input[i]= '\0';returninput;
}
i++;
}
}returnNULL;
}
编译:gcc cgitest.c -o /cgitest.cgi
打开浏览器访问:http://192.168.10.121点击test
附上我的路径:
哈哈哈哈哈哈哈~大功告成,牛逼坏了~
总结:cgi可以放到./或../ 或../test/ 都行,只要不高于web服务器就行。后缀名必须是.cgi,这个与web服务器的约定有关系。
这里所使用的是httpd,理论上是可以用tomcat,nginx,weblogic等,甚至可以用自己写的web容器,如简单的tinyhttd,共500行代码。