环境:centos 6.5
web容器:apache2.4,[<http://httpd.apache.org/docs/2.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
<html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <h1>It works!hahahahhahaha~</h1> <input type="button" onclick="testcgi()" value="test"/> </body> <script type = "text/javaScript"> function testcgi(){ $.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); } }); } </script> </html>
在/usr/local/apache/cgi-bin添加 cgitest.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #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 " ); 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; int len; int size = MAXLEN; int i = 0; if (!strcmp(requestmethod, "GET")) { input = getenv("QUERY_STRING"); return input; } else if (!strcmp(requestmethod, "POST")) { len = atoi(getenv("CONTENT_LENGTH")); input = (char*)malloc(sizeof(char)*(size + 1)); if (len == 0) { input[0] = '